Extending the Enum
example here, I can add a class method to select the correct enum when only part of its tuple is supplied:
class Planet1(Enum):
MERCURY = (3.303e23, 2.4397e6)
VENUS = (4.869e24, 6.0518e6)
EARTH = (5.976e24, 6.37814e6)
MARS = (6.421e23, 3.3972e6)
@classmethod
def from_partial(cls, mass=None, radius=None):
for member in cls:
if member.mass == mass or member.radius == radius:
return member
raise ValueError("No planet with these characteristics.")
def __init__(self, mass, radius):
self.mass = mass # in kg
self.radius = radius # in m
p1 = Planet1.MARS
p2 = Planet1.from_partial(6.421e23)
p3 = Planet1.from_partial(radius=3.3972e6)
p1 is p2 is p3 # True
I'd like to be able to select one without using the .from_partial()
method though. Is that possible?
What I've tried:
class Planet2(Enum):
MERCURY = (3.303e23, 2.4397e6)
VENUS = (4.869e24, 6.0518e6)
EARTH = (5.976e24, 6.37814e6)
MARS = (6.421e23, 3.3972e6)
def __init__(self, mass=None, radius= None):
if mass is None or radius is None:
for member in Planet2:
if member.mass == mass or member.radius == radius:
self.__dict__ = member.__dict__
else:
self.mass = mass # in kg
self.radius = radius # in m
p2a = Planet2.MARS
p2b = Planet2(6.421e23) # ValueError: 6.421e+23 is not a valid Planet2
p2c = Planet2(radius=3.3972e6) # TypeError: __call__() got an unexpected keyword argument 'radius'
Is there a way to do this, or does this go against what Enums are intended to be used for? The self.__dict__ = member.__dict__
looks dodgy, but I'd have thought it would work :)