Python中模擬enum列舉型別的5種方法分享

2022-10-04 23:42:11 字數 991 閱讀 7006

以下幾種方法來模擬enum:(感覺方法一簡單實用)

複製** **如下:

# way1

class directions:

up = 0

down = 1

left = 2

right =3

print directwww.cppcns.comions.dow程式設計客棧n

# way2

dirup, dirdown, dirleft, dirright = range(4)

print dirdown

# way3

import collections

dircoll=collections.namedtuple('directions', ('up', 'down', 'left', 'right'))

directions=dircoll(0,1,2,3)

print directions.down

# way4

def enum(args, start=0):

class enum(object):

__slots__ = args.split()

def __init__(self):

for i, key in enumerate(enum.__slots__, start):

www.cppcns.com       setattr(self, key, i)

www.cppcns.com;  return enum()

e_dir = enum('up down left right')

print e_dir.down

# way5

# some times we need use enum value as string

directions =

print direct程式設計客棧ions['down']

本文標題: python中模擬enum列舉型別的5種方法分享

本文位址:

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

python中沒有enum列舉型別,可能python認為這玩意壓根就沒用,下面列舉了三種方法模擬enum列舉型別 方法1.使用自定義類 class numbers object one 1 two 2 th 3 assert numbers.one 1 assert numbers.two 2 as...

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...