第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

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

使用元類構(gòu)建 Python 枚舉類

使用元類構(gòu)建 Python 枚舉類

開滿天機 2021-09-28 20:44:32
出于某種原因,在周日早上,我覺得我正在編寫的科學(xué)圖書館需要以下內(nèi)容: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基本上不是傳遞參數(shù)polarity='POSITIVE'和檢查字符串,也因為我使用類型提示,我希望它是強類型的,我寫了上面的代碼。這是否有意義,是否有更簡單/更清潔/更好的方法來實現(xiàn)相同的結(jié)果?
查看完整描述

1 回答

?
交互式愛情

TA貢獻(xiàn)1712條經(jīng)驗 獲得超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


查看完整回答
反對 回復(fù) 2021-09-28
  • 1 回答
  • 0 關(guān)注
  • 186 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學(xué)習(xí)伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號