python模擬enum列舉型別的方法小結

2022-10-04 23:00:26 字數 1042 閱讀 6714

python中沒有enum列舉型別,可能python認為這玩意壓根就沒用,下面列舉了三種方法模擬enum列舉型別

方法1. 使用自定義類

class numbers(object):

one = 1

two = 2

th = 3

assert numbers.one == 1

assert numbers.two == 2

assert numbers.three == 3

方法2:www.cppcns.com使用函式動態建立類

def enum(**enums):

return type('enum', (object,), enums)

numbers = enum(one=1, two=2, three=3)

assert numbers.one == 1

assert numbers.two == 2

assert numbers.yrpzvthree == 3

方法3:建立乙個從python的集合擴充套件來的物件

class enum(set):

def __getattr__(self, name):

if name in self:

return name

raise attributeerror

numbers = enum( "one two three".split() )

error = false

try:

print numbers.one

print numbers.two

p程式設計客棧rint numbers.three

except:

error = true

assert error == false

try:

print numbers.four

except:

error = true

assert error == true

本文標題: python模擬enum列舉型別的方法小結

本文位址:

python的列舉類 Enum

列舉 from enum import enum,unique 1 預設列舉類 month enum month jan feb mar for name,member in month.members items print name,member,member.value value屬性是自動賦...

Python列舉類(Enum 學習

an enumeration is a set of symbolic names members bound to unique,constant values.within an enumeration,the members can be compared by identity,and th...

enum列舉類使用例項

package com.elk.wsl.enums author 胖子不胖 description 使用與碼值的轉換 date created in 21 26 2019 2 18 modified by public enum color public string getenglish publ...