出于某种原因,在周日早上,我觉得我正在编写的科学图书馆需要以下内容: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.Pclass Polarity(metaclass=PolarityType): """Base class to build polarity.""" P = 0class PositivePolarity(Polarity): """Positive polarity.""" P = 1class NegativePolarity(Polarity): """Negative polarity.""" P = -1>>> float(NegativePolarity)>>> -1.0基本上不是传递参数polarity='POSITIVE'和检查字符串,也因为我使用类型提示,我希望它是强类型的,我写了上面的代码。这是否有意义,是否有更简单/更清洁/更好的方法来实现相同的结果?
1 回答
交互式爱情
TA贡献1712条经验 获得超3个赞
您的解决方案有效,但是否有特殊原因不使用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
添加回答
举报
0/150
提交
取消