Reputation: 8288
For some reason, on a Sunday morning I felt like I needed the following for a scientific library I'm writing:
class PolarityType(type):
"""Metaclass to construct polarity types. Supports conversion to float and int."""
def __float__(cls):
return int(cls)
def __int__(cls):
return cls.P
class Polarity(metaclass=PolarityType):
"""Base class to build polarity."""
P = 0
class PositivePolarity(Polarity):
"""Positive polarity."""
P = 1
class NegativePolarity(Polarity):
"""Negative polarity."""
P = -1
>>> float(NegativePolarity)
>>> -1.0
Basically instead of passing arguments like polarity='POSITIVE'
and checking strings, and also because I'm using type hints, I wanted it to be strongly typed and I wrote the above code.
Does it make sense, is there a much easier/cleaner/better way to achieve the same result?
Upvotes: 1
Views: 361
Reputation: 744
Your solution works, but is there a special reason not to use an enum?
import enum
class Polarity(enum.Enum):
POSITIVE: float = 1.0
NEGATIVE: float = -1.0
def __float__(cls):
return self.value
def __int__(cls):
return int(self.value)
print(Polarity.NEGATIVE, type(Polarity.NEGATIVE))
# Polarity.NEGATIVE <enum 'Polarity'>
print(type(Polarity.NEGATIVE.value), Polarity.NEGATIVE.value)
# <class 'float'> -1.0
print(type(float(Polarity.NEGATIVE)), float(Polarity.NEGATIVE))
# <class 'float'> -1.0
Upvotes: 4