In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-15 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
This article mainly introduces "how to use enum in Python". In daily operation, I believe many people have doubts about how to use enum in Python. The editor consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful for you to answer the doubts about "how to use enum in Python". Next, please follow the editor to study!
Foreword:
Enumeration is often expressed as a basic data structure in many programming languages. Enumeration helps organize a series of closely related members into the same group mechanism. Generally, various discrete attributes can be defined by enumerated data structures, such as color, season, country, time unit, etc.
There are no built-in enumeration methods in Python, and the initial way to mimic the implementation of enumerated properties is
Class Directions: NORTH = 1 EAST = 2 SOUTH = 3 WEST = 4
Use members:
Direction.EAST
Direction.SOUTH
Check members:
> print ("North type:", type (Direction.NORTH)) > print (isinstance (Direction.EAST, Direction)) North type: False
The type of the member NORTH is int, not Direction, which simply defines the property into the class
Python standard library enum implements the function of enumerating attributes, and then introduces the use of enum in actual production.
1. Why use enum and when to use enum?
Enum specifies the properties of a limited set, which limits the use of values within the collection, explicitly declares which values are legal values, and causes an error if you enter illegal values. You can use enum to organize values as long as you want to take values from a limited collection.
Definition / declaration of 2.enum from enum import Enumclass Directions (Enum): NORTH = 1 EAST = 2 SOUTH = 3 WEST = 4
Usage and type checking:
> Directions.EAST > Directions.SOUTH > > Directions.EAST.name'EAST' > Directions.EAST.value2 > print ("South type:", type (Directions.SOUTH)) South type: > print (isinstance (Directions.EAST, Directions)) True >
Check the type of the sample South, and the result is Directions as expected. Name and value are two useful additional attributes.
It may be used in practice as follows:
Fetched_value = 2 # get the value if Directions (fetched_value) is Directions.NORTH:... elif Directions (fetched_value) is Directions.EAST:... else:.
When entering an undefined value:
Directions (5) ValueError: 5 is not a valid Directions3. Traversing member > for name, value in Directions.__members__.items ():... Print (name, value)... NORTH Directions.NORTHEAST Directions.EASTSOUTH Directions.SOUTHWEST Directions.WEST4. Methods defined in classes that inherit Enum
Can be used to convert a defined value to get the desired value
From enum import Enumclass Directions (Enum): NORTH = 1 EAST = 2 SOUTH = 3 WEST = 4 def angle (self): right_angle = 90.0 return right_angle * (self.value-1) @ staticmethod def angle_interval (direction0, direction1): return abs (direction0.angle ()-direction1.angle ()) > > east = Directions.EAST > > print ("SOUTH Angle:" East.angle () SOUTH Angle: 90.0 > west = Directions.WEST > print ("Angle Interval:", Directions.angle_interval (east, west)) Angle Interval: 180.05. Define the value of a property of the Enum class as a function or method from enum import Enumfrom functools import partialdef plus_90 (value): return Directions (value). Angle + 90class Directions (Enum): NORTH = 1 EAST = 2 SOUTH = 3 WEST = 4 PLUS_90 = partial (plus_90) def _ call__ (self, * args, * * kwargs): return self.value (* args * * kwargs) @ property def angle (self): right_angle = 90.0 return right_angle * (self.value-1) print (Directions.NORTH.angle) print (Directions.EAST.angle) south = Directions (3) print ("SOUTH angle:", south.angle) print ("SOUTH angle plus 90:", Directions.PLUS_90 (south.value))
Output:
0.0
90.0
SOUTH angle: 180.0
SOUTH angle plus 90: 270.0
Key: 1. Wrap the function method in partial; 2. Define the _ _ call__ method.
Ignore case:
Class TimeUnit (Enum): MONTH = "MONTH" WEEK = "WEEK" DAY = "DAY" HOUR = "HOUR" MINUTE = "MINUTE" @ classmethod def _ missing_ (cls, value: str): for member in cls: if member.value = = value.upper (): return memberprint (TimeUnit ("MONTH")) print (TimeUnit ("Month"))
Inherit the _ missing_ method of the parent class Enum, and change the case to consistent when comparing values.
Output:
TimeUnit.MONTH
TimeUnit.MONTH
6. Custom exception handling
First, you want to throw a custom error when you execute SomeEnum ("abc"), where "abc" is an undefined property value.
Class TimeUnit (Enum): MONTH = "MONTH" WEEK = "WEEK" DAY = "DAY" HOUR = "HOUR" MINUTE = "MINUTE" @ classmethod def _ missing_ (cls, value: str): raise Exception ("Customized exception") print (TimeUnit ("MONTH") TimeUnit ("abc")
Output:
TimeUnit.MONTH
ValueError: 'abc' is not a valid TimeUnit
...
Exception: Customized exception
Second: when executing SomeEnum.__getattr__ ("ABC"), you want to raise a custom error, where "ABC" is an undefined property name. You need to override the _ _ getattr__ method in EnumMeta, and then specify the metaclass of the instance Enum object.
From enum import Enum, EnumMetafrom functools import partialclass SomeEnumMeta (EnumMeta): def _ _ getattr__ (cls, name: str): value = cls.__members__.get (name.upper ()) # (where name is the attribute name, you can customize to pass in uppercase (or lowercase) Corresponding to the following A1 is uppercase) if not value: raise Exception ("Customized exception") return valueclass SomeEnum1 (Enum, metaclass=SomeEnumMeta): A1 = "123" class SomeEnum2 (Enum, metaclass=SomeEnumMeta): A1 = partial (lambda x: X) def _ call__ (self, * args, * * kwargs): return self.value (* args) * * kwargs) print (SomeEnum1.__getattr__ ("A1")) print (SomeEnum2.__getattr__ ("A1") ("123")) print (SomeEnum2.__getattr__ (" B ")
Output:
SomeEnum1.A1
one hundred and twenty three
...
Exception: Customized exception
Advanced usage of 7.enum Functional APIs
To dynamically create and modify Enum objects, you can add modifications without modifying the originally defined Enum class. Here is an illustrative example. For specific scenario use cases, please see the following scenario example.
> # Create an Enum class using the functional API... DirectionFunctional = Enum ("DirectionFunctional", "NORTH EAST SOUTH WEST", module=__name__). # Check what the Enum class is... Print (DirectionFunctional)... # Check the items... Print (list (DirectionFunctional)). Print (DirectionFunctional.__members__.items ())... Dict_items ([('NORTH',), (' EAST',), ('SOUTH',), (' WEST',)]) > # Create a function and patch it to the DirectionFunctional class... Def angle (DirectionFunctional):... Right_angle = 90. 0. Return right_angle * (DirectionFunctional.value-1)... ...... DirectionFunctional.angle = angle... ... # Create a member and access its angle... South = DirectionFunctional.SOUTH... Print ("South Angle:", south.angle ())... South Angle: 180.0
Note: instead of using the method of direct class declaration to perform enumerations (if you do not specify a number that starts with 1 by default, which is equivalent to NORTH = auto (), auto is a method in enum), you can still create a method for this dynamically created DirectionFunctional later, which modifies the object while running, which is python's monkey patching.
Examples of the uses and usage scenarios of Functional APIs:
Without modifying the code block of a defined Enum class, the following example is the Arithmethic class, which can be considered as a source code library. We do not want to modify it, and then add the attributes of the Enum class. There are two ways:
The properties of the 1.enum.Enum object cannot be modified directly, but we can dynamically create a new Enum class to extend the original Enum object.
For example, to add a modulo member MOD= "%" to the following Enum object Arithmetic, but you cannot modify the code block in the Arithmetic class:
# enum_test.pyfrom enum import Enumclass Arithmetic (Enum): ADD = "+" SUB = "-" MUL = "*" DIV = "/"
You can use the Functional APIs method of enum:
# functional_api_test.pyfrom enum import EnumDynamicEnum = Enum ("Arithmetic", {"MOD": "%"}, module= "enum_test", qualname= "enum_test.Arithmetic") print (DynamicEnum.MOD) print (eval (f "5 {DynamicEnum.MOD.value} 3"))
Output:
Arithmetic.MOD
two
Note: when creating an Enum object dynamically, specify the module name of the original Enum class: "Yourmodule". Otherwise, the qualname may not be able to parse because the source cannot be found. The qualname should specify the location of the class: "Yourmodule.YourEnum". The value uses a string type.
two。 Using aenum.extend_enum, you can dynamically modify enum.Enum objects
Add an exponential member EXP= "*" to the enum.Enum class Arithmetic without modifying the code block of the original Arithmetic class:
# functional_api_test.pyfrom aenum import extend_enumfrom enum_test import Arithmeticextend_enum (Arithmetic, "EXP", "*") print (Arithmetic, list (Arithmetic)) print (eval (f "2 {Arithmetic.EXP.value} 3"))
Output:
[,]
eight
At this point, the study on "how to use enum in Python" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.