Reputation: 4524
I defined the following Enum in Python:
class Unit(Enum):
GRAM = ("g")
KILOGRAM = ("kg", GRAM, 1000.0)
def __init__(self, symbol, base_unit = None, multiplier = 1.0):
self.symbol = symbol
self.multiplier = multiplier
self.base_unit = self if base_unit is None else base_unit
I would expect that
print(Unit.GRAM.base_unit)
print(Unit.KILOGRAM.base_unit)
will return
Unit.GRAM
Unit.GRAM
However, what I get is quite confusing
Unit.GRAM
g
Why is it so?
Upvotes: 6
Views: 162
Reputation: 69288
DavidZ explained the problem well.
The last bit that you need to solve this problem is this: when the __init__
of each member is being run, the Enum
has been created -- so you can call it:
self.base_unit = self if base_unit is None else self.__class__(base_unit)
Upvotes: 1
Reputation: 131780
The way Python defines a class involves creating a new scope, processing a bunch of statements (variable assignments, function definitions, etc.), and then actually creating a class object based on the local variables which exist after all those statements have run. Nothing gets converted into Enum
instances until that last step.
You could understand it somewhat like this:
def make_class_Unit():
GRAM = ("g")
KILOGRAM = ("kg", GRAM, 1000.0)
def __init__(self, symbol, base_unit = None, multiplier = 1.0):
self.symbol = symbol
self.multiplier = multiplier
self.base_unit = self if base_unit is None else base_unit
return make_class(name='Unit', base=Enum, contents=locals())
Unit = make_class_Unit()
Looking at it this way, hopefully you can tell that at the time when KILOGRAM
is defined, GRAM
is really just a string. It doesn't become a Unit
instance until the last stage, where I call the (imaginary) make_class()
function.1
1Even though the make_class
function I used above doesn't actually exist under that name, it's not too different from what Python really does, which is calling the constructor of type
or a metaclass (which in this case is the metaclass for Enum
s).
Upvotes: 3