简体   繁体   中英

Python 3: Add Enum attributes to class scope

In Python 3.10+ is there a way to add the attributes ( RED in this case) to the scope of a class ( MyClass in this case) like this:


    class Color(Enum):
        RED = 1
    class MyClass():
        def myMethod(self, t):
            return t is RED # instead of return t is Color.RED

Without

  1. adding RED to the global scope eg like this: globals().update(Color.__members__)
  2. adding some initialization code to every class method (eg like the above; but locals() cannot be updated in that fashion anyway as far as I know)

You must use this sintax:

enum_class.enum => Color.RED


I also found this in Python's doc:

Comparisons against non-enumeration values will always compare not equal (again, IntEnum was explicitly designed to behave differently)

Color.BLUE == 2 => False


You must use IntEnum.

from enum import IntEnum

class Color(IntEnum):
    RED = 1
    
class MyClass():
    def myMethod(self, t):
        return Color.RED == 1 # Use 'enum_class.enum' to access to your attribute

print(MyClass().myMethod(1)) # True

This is the pythonic way:

class Color(Enum):
    RED = 1

class MyClass():

    RED = Color.RED

    def my_method(self, t):
        return t is self.RED

Also, you can make my_method a @classmethod .

When the RED attribute is bound to the class like this, it also plays nicely with inheritence. Eg subclasses can override it.

The following is more in line with your question, yet less recommended IMO:

class Color(Enum):
    RED = 1

RED = Color.RED

class MyClass():
    def my_method(self, t):
        return t is RED

There is no class scope. Classes have a namespace, but no other code can access it automatically and directly, they always must access it via the class name, or via self inside a method.

If you added RED as a class variable, you'd need to use either MyClass.RED or self.RED in the method, which doesn't seem much better than accessing it via Color .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM