Cara menggunakan python string to enum

Java enum adalah singkatan dari enumeration. Ini pertama kali diterapkan dalam pembaruan Java 5. Enums adalah keyboard di JAVA yang digunakan untuk menggambarkan kumpulan konstanta dalam suatu program. Enum membalas kerja kelas. Itu dapat dianggap sebagai kelas khusus yang dapat berisi komponen kelas konvensional seperti metode, konstanta, dll. Untuk mendefinisikan kelas enum, keyboard 'enum' harus dilampirkan dalam definisi. Contoh deklarasi enum diberikan di bawah ini.

Enum menemukan penggunaan terbaik ketika semua hasil yang mungkin diketahui oleh pengembang. Enum bertindak sebagai nilai konstan di seluruh cakupannya. Namun, ini tidak berarti bahwa nilai tidak dapat ditimpa. Tidak seperti C/C++ enum, enum Java dapat memiliki variabel, metode, dan konstruktor sehingga membuatnya lebih kuat dengan mengaitkan perilaku ke dalamnya.

Sintaks Enum JAVA

Enumerasi dalam Java dapat dideklarasikan baik di dalam maupun di luar kelas. Satu-satunya batasan untuk deklarasinya adalah ia tidak dapat dideklarasikan di dalam metode karena metode umumnya tidak memiliki cakupan kelas yang begitu besar.

Mari kita lihat dua contoh di mana JAVA Enum telah dideklarasikan di dalam dan di luar kelas.

  • Di luar kelas

    enum Pizza
    {
    KEJU, AYAM, JALAPENO
    }
    Topping kelas publik
    {
    public static void main (String [] args)
    {
    Pizza t = Pizza.KEJU;
    out.println (“Topping yang dipilih adalah” + t);
    }OUTPUT: KEJU
  • Di dalam kelas

    Topping kelas publik
    {
    enum Pizza
    {
    KEJU, AYAM, JALAPENO
    }
    public static void main (String [] args)
    {
    Pizza t = Pizza.KEJU;
    out.println (“Topping yang dipilih adalah” + t);
    }OUTPUT: KEJU

Contoh

//Contoh ini adalah program Switch Case sederhana yang akan memperluas penggunaan Enum seperti yang dijelaskan //sebelumnya. impor java.util.Scanner; enum Pizza { KEJU, AYAM, JALAPENO } kelas publik Contoh { Pizza top; //Constructor public Sample (Pizza top) { this.top = top; } //Mengimplementasikan switch case public void pizzaTopping () { switch (atas) { case CHEESE: System.out.println (“Topping yang Anda pilih di Cheese”); merusak; case CHICKEN: System.out.println (“Topping yang Anda pilih pada Ayam”); merusak; case JALAPENO: System.out.println (“Topping yang Anda pilih di Jalapeno”); merusak; default: System.out.println (“Tidak ada topping yang dipilih. Coba lagi”); merusak; } } public static void main (String [] args) { String str = “CHEESE”; Bendera sampel = Sampel baru (Pizza.valueOf(str)); flag.pizzaTopping(); } }

Berbagai Metode kelas JAVA Enum

Untuk dapat menggunakan metode yang disebutkan di bawah, seseorang perlu mengimpor paket java.lang.Enum.

Advertisements
  • values() – Metode ini mengembalikan nilai semua konstanta yang merangkum JAVA Enum.
  • ordinal () – Metode ordinal () mengembalikan nomor indeks setiap enum seolah-olah enum adalah struktur data seperti array. Ini digunakan untuk membuat semacam hierarki.
  • valueOf() – Jika ada, metode ini mengembalikan konstanta enum dari nilai string.
  • Advertisements

Mari kita lihat contoh di mana semua metode ini digunakan dalam Enum.

enum Pizza { CHEESE, CHICKEN, JALAPENO } public class Demo { public static void main (String [] args) { //Menetapkan array dengan nilai enum Pizza arr [] = Pizza.values(); for(Pizza top : arr) { //Untuk mencetak nomor indeks dari setiap enum System.out.println(top + “index no:” + top.ordinal()); //Akhirnya, kita akan mengembalikan nilai salah satu enum menggunakan metode valueof() System.out.println (Pizza.valueOf (“CHICKEN”) ); } }

KELUARAN

nomor indeks KEJU: 0
AYAM indeks no: 1
Nomor indeks JALAPENO: 2
AYAM

Perbedaan antara kelas dan JAVA Enum

Meskipun Java Enum, seperti halnya kelas dapat memiliki metode dan variabel, anggota enum harus bersifat publik, statis, dan final. Di kelas, pengguna memiliki kebebasan untuk menjaga ruang lingkup anggota tetap fleksibel.

There are four module content or Enumeration classes that are used to define unique sets of values and names. The four enumeration classes are IntFlag, Flag, IntEnum, and Enum. Moreover, it also provides a helper, auto, and a decorator, Unique(). Enum class is created as ‘class enum.Enum’. It is a base class that is utilized to create enumerated constants. IntEnum class is created as ‘class enum.IntEnum’. The IntEnum enumeration class is another base class used to create enumerated constants, the subclasses of int. The next class is Flag, which is created as ‘class enum.Flag’.

Flag creates the enumerated constants that can be combined by using bitwise operations without losing the Flag membership. The IntFlag enumeration class has the same functionality as the Flag enumeration class. It also creates enumerated constants that bitwise operators can combine without losing the IntFlag membership. The decorator, unique() is created as ‘enum.unique()’, which ensures that only value is associated with one name. Last but not least, the helper auto is created as ‘class enum.auto’. It is used to replace the instances of Enum members with a suitable value. However, the starting value begins at 1, by default.

Example 1:

Our first example is about creating the enum class. As it is observed that Enums are created using the class syntax, which makes it easy to write and read. Enums are extremely helpful where one variable can acquire one of a partial collection of values. Here is an instance of how to define an Enum class:

from enum import Enum

class Months(Enum):

    JANUARY = 1
    FEBURARY = 2
    MARCH = 3
    APRIL = 4
    MAY = 5
    JUNE = 6

Notice that creating an Enum class itself is very simple, just like writing a class that is inherited from Enum itself. Moreover, the value of an Enum’s member may or may not be essential; however, either way, the member’s value is used to extract the corresponding member. Look at the example given below:

Cara menggunakan python string to enum

When you call the member of Enum ‘Months’, you will get the following output:

Cara menggunakan python string to enum

Example 2:

The other way to get the Enum’s member is shown in the example below:

Months.MAY

Here is the output of the above statement.

Cara menggunakan python string to enum

As you can see, both ways you can get the members of Enum class.

Note: the values of Enum members could be anything; str, int, etc. when the exact value is not important, the instances of helper ‘auto’ can be used so that a suitable value can be chosen. However, you need to be careful while mixing ‘auto’ helper with other values.

Example 3:

You can observe that creating and defining Enum is very simple, just like creating or defining any other class. However, here we have a simple example to help you understand converting python string to Enum. Let us run the code given below and see what we get after executing it:

from enum import Enum

class Profit(Enum):
    PURCHASE = 50000
    SALE = 10000
Profit['PURCHASE']

Copy-paste the code or make your own customized Enum class by simply following the directions and seeing the output. Enter the subsequent command to convert the python string to enum.

Cara menggunakan python string to enum

The following output will be produced when you enter the code given above:

Cara menggunakan python string to enum

Example 4:

Another example of converting the python string to Enum is given below:

class stringEnum(Enum):
    x = 'abc'
    y = 456
print(stringEnum('abc'), stringEnum(456))

When you execute the above statements, you will get the following output:

Cara menggunakan python string to enum

As you can see, the string is converted to both str() and int(). The value of Enum member can be extracted in either way.

Conclusion:

This article uses the correct way to convert the python string to enum. First, we have discussed what Enum is and how it can be used. There are four classes of Enumeration; Enum, IntEnum, Flag, IntFlag, and there is one helper, ‘auto’, and one decorator, unique(). Enumeration classes are bases classes used to create enumerated constants. The helper ‘auto’ is used to replace the instances of Enum members with a suitable value. While the decorator, unique() is used to ensure that only one value is allocated to a name. After discussing the enumeration classes, we have learned how to create an Enum class and how it can be used for python string to enum conversion. This article will help you understand the python string conversion to Enum and will guide you to make your own Enum classes without making any mistakes. Follow the directions and start making your enum classes for python string to enum conversion.