亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

使用元類構建 Python 枚舉類

使用元類構建 Python 枚舉類

開滿天機 2021-09-28 20:44:32
出于某種原因,在周日早上,我覺得我正在編寫的科學圖書館需要以下內容: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


查看完整回答
反對 回復 2021-09-28
  • 1 回答
  • 0 關注
  • 193 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號