python--enum

來源:互聯網
上載者:User

標籤:rom   from   結果   false   enum   通過   val   class   print   

# enum用於枚舉,該模組下有一個Enum,我們定義的類要繼承它# 一旦繼承,那麼我們定義的key(仮),不能有重複值。# 如果要保證value(仮)不重複,那就引入unique,給我們定義的類加上這個裝飾器from enum import Enum, unique@uniqueclass Color(Enum):    red = 1    green = 2    blue = 3    yellow = 4    pink = 5    cyan = 6# 通過名稱擷取成員,兩種方式print(Color["red"])  # Color.redprint(Color.red)  # Color.red# 通過值來擷取成員print(Color(2))  # Color.green# 擷取成員的名稱和值print(Color.red.name)  # redprint(Color.red.value)  # 1# 也可以通過迭代擷取成員for color in Color:    print(color.name, color.value)‘‘‘red 1green 2blue 3yellow 4pink 5cyan 6‘‘‘

  

# 如果不加上unique,也就允許值相同會有什麼情況from enum import Enumclass Girls(Enum):    satori = 1    mashiro = 2    nagisa = 3    tomoyo = 4    kurisu = 5    sola = 1# satori 和sola的值都是1print(Girls(1))  # Girls.satori,會發現只列印了satori,也就是第一個。如果值相同,那麼後者相當於是前者的別名。# 遍曆的話,會發現sola同樣沒有被列印出來for girl in Girls:    print(girl)‘‘‘Girls.satoriGirls.satoriGirls.mashiroGirls.nagisaGirls.tomoyoGirls.kurisu‘‘‘# 如果想擷取所有的成員,哪怕值相同,該怎麼做呢?# 枚舉屬性內部有一個__members__屬性,相當於一個字典for girl in Girls.__members__.items():    print(girl)‘‘‘(‘satori‘, <Girls.satori: 1>)(‘mashiro‘, <Girls.mashiro: 2>)(‘nagisa‘, <Girls.nagisa: 3>)(‘tomoyo‘, <Girls.tomoyo: 4>)(‘kurisu‘, <Girls.kurisu: 5>)(‘sola‘, <Girls.satori: 1>)‘‘‘# 會發現以一種更詳細的方式列印了出來# 並且每個元組的第二個元素是<enum ‘Girls‘>類型# 不要被<>給忽悠了,其實就是我們用Girls.satori,Girls.mashiro ····擷取得到的結果for girl in Girls.__members__.items():    print(girl[1].name, girl[1].value)‘‘‘satori 1mashiro 2nagisa 3tomoyo 4kurisu 5satori 1‘‘‘# 成員之間也可以進行比較,但只能用==,is等操作符,不支援大小比較print(Girls.satori is Girls.mashiro)  # Falseprint(Girls.satori == Girls.mashiro)  # Falseprint(Girls.satori is Girls.sola)  # True,因為兩者值一樣,後者是前者的別名,兩個指標指向了同一個地方print(Girls.satori is Girls.sola)  # True# 如果把1換成列表的話class Girls(Enum):    satori = [1, 2]    mashiro = 2    nagisa = 3    tomoyo = 4    kurisu = 5    sola = [1, 2]    kurumi = [1, 2]print(Girls.satori is Girls.sola)  # Trueprint(Girls.satori is Girls.sola)  # Trueprint(Girls.kurumi is Girls.sola)  # True# 會發現仍舊是True,儘管列表是可變類型,但如果值一樣,會繼續讓sola的指標指向satori的指標所指向的記憶體# 因為值一樣,那麼sola就看做是satori的引用# 同理再加上一個kurumi是一樣的結果# 不用__members__的話,列印的仍然是第一個satori

  

python--enum

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.