猿问

使用元类构建 Python 枚举类

出于某种原因,在周日早上,我觉得我正在编写的科学图书馆需要以下内容:


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

基本上不是传递参数polarity='POSITIVE'和检查字符串,也因为我使用类型提示,我希望它是强类型的,我写了上面的代码。


这是否有意义,是否有更简单/更清洁/更好的方法来实现相同的结果?


开满天机
浏览 175回答 1
1回答

交互式爱情

您的解决方案有效,但是否有特殊原因不使用enum?import enumclass Polarity(enum.Enum):&nbsp; &nbsp; POSITIVE: float = 1.0&nbsp; &nbsp; NEGATIVE: float = -1.0&nbsp; &nbsp; def __float__(cls):&nbsp; &nbsp; &nbsp; &nbsp; return self.value&nbsp; &nbsp; def __int__(cls):&nbsp; &nbsp; &nbsp; &nbsp; 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.0print(type(float(Polarity.NEGATIVE)), float(Polarity.NEGATIVE))# <class 'float'> -1.0
随时随地看视频慕课网APP

相关分类

Python
我要回答