Sub topic 7
Adding methods, properties and fields to members
This chapter assumes you know Python classes, instance methods, @property, and how to define Enum classes with .name and .value. Enum members are real objects, so they can carry behavior and extra data.
Methods on members
An enum class is a class, so you can define methods in it. Inside a method, self is the member the method was called on.
from enum import Enum
class Weekday(Enum):
MON = 1
TUE = 2
WED = 3
THU = 4
FRI = 5
SAT = 6
SUN = 7
def is_weekend(self):
return self in (Weekday.SAT, Weekday.SUN)
@classmethod
def from_label(cls, label):
return cls[label.upper()]
print(Weekday.SAT.is_weekend()) # True
print(Weekday.MON.is_weekend()) # False
print(Weekday.from_label("fri")) # Weekday.FRIFunctions, properties, classmethods and staticmethods are descriptors. Python does not turn them into members. Any other plain assignment in the class body does become a member.
Fields from tuple values
To give each member several pieces of data, use a tuple as its value. Then define __init__ to unpack the tuple into attributes.
from enum import Enum
G = 6.67300e-11 # module-level, so it is not an enum member
class Planet(Enum):
MERCURY = (3.303e+23, 2.4397e6)
EARTH = (5.976e+24, 6.37814e6)
def __init__(self, mass, radius):
self.mass = mass
self.radius = radius
@property
def surface_gravity(self):
return G * self.mass / (self.radius * self.radius)
print(round(Planet.EARTH.surface_gravity, 1)) # 9.8
print(Planet.EARTH.mass) # 5.976e+24
print(Planet.EARTH.value) # (5.976e+24, 6371...)Python calls __init__ once per member when the class is created. It passes the unpacked tuple as arguments. The attributes mass and radius are set on the member, and .value is still the original tuple.
Lookups still use the full value
Because .value is the whole tuple, a lookup by value must supply the whole tuple.
print(Planet((5.976e+24, 6.37814e6))) # Planet.EARTHAliases follow the same rule. Two names with equal tuples refer to the same member.
Separating the value from the data
Sometimes you want a simple value, such as an integer, and extra data besides. You can give the tuple a leading identifier and let __new__ choose the real value. The simpler option is to keep a plain value and store the extra data in a lookup dictionary outside the class. Use __new__ only if you need the value to differ from the tuple.
from enum import Enum
class Http(Enum):
OK = (200, "OK")
NOT_FOUND = (404, "Not Found")
def __new__(cls, code, phrase):
obj = object.__new__(cls)
obj._value_ = code
obj.phrase = phrase
return obj
print(Http(404)) # Http.NOT_FOUND
print(Http.OK.value) # 200
print(Http.OK.phrase) # OKSetting _value_ inside __new__ makes .value the code, and lookups use Http(404). When __new__ is defined, __init__ is not needed here.
Common mistakes
- Mutating attributes after creation. Members are shared singletons. If you change
Planet.EARTH.mass, every part of the program sees the change. Treat fields as read-only. - Forgetting that
__init__receives unpacked arguments. If a value is a tuple of two items,__init__must accept exactly two parameters. A mismatch raisesTypeErrorwhen the class is defined. - Using a property name as a member name. Defining a property and a member with the same name in one body causes a conflict. Pick distinct names.
Exercise
Given the class below, what does Size.SMALL.value return, and what does Size.SMALL.label return? Why does Size(1) raise ValueError?
class Size(Enum):
SMALL = (1, "S")
LARGE = (2, "L")
def _init_(self, number, label):
self.number = number
self.label = label
Show answer
Size.SMALL.value is the whole tuple (1, "S"), and Size.SMALL.label is "S". Size(1) raises ValueError because lookup compares against the full tuple value, and 1 does not equal (1, "S"). Use Size((1, "S")), or define __new__ and set _value_ = number so that Size(1) works.