รายการซ้ำที่เป็นไปได้:
ฉันจะทำอย่างไร เป็นตัวแทนของ 'enum' ใน Python?
แนวปฏิบัติทั่วไปสำหรับ enum ใน Python คืออะไร เช่น. พวกมันถูกจำลองแบบใน Python อย่างไร?
public enum Materials
{
Shaded,
Shiny,
Transparent,
Matte
}
รายการซ้ำที่เป็นไปได้:
ฉันจะทำอย่างไร เป็นตัวแทนของ 'enum' ใน Python?
แนวปฏิบัติทั่วไปสำหรับ enum ใน Python คืออะไร เช่น. พวกมันถูกจำลองแบบใน Python อย่างไร?
public enum Materials
{
Shaded,
Shiny,
Transparent,
Matte
}
ฉันเคยเห็นรูปแบบนี้หลายครั้ง:
>>> class Enumeration(object):
def __init__(self, names): # or *names, with no .split()
for number, name in enumerate(names.split()):
setattr(self, name, number)
>>> foo = Enumeration("bar baz quux")
>>> foo.quux
2
คุณยังสามารถใช้สมาชิกชั้นเรียนได้ แต่คุณจะต้องระบุหมายเลขของคุณเอง:
>>> class Foo(object):
bar = 0
baz = 1
quux = 2
>>> Foo.quux
2
หากคุณกำลังมองหาบางสิ่งที่แข็งแกร่งกว่านี้ (ค่ากระจัดกระจาย ข้อยกเว้นเฉพาะ enum ฯลฯ) ลองสิ่งนี้ สูตร.
ฉันไม่รู้ว่าทำไม Enums ถึงไม่รองรับ Python โดยกำเนิด วิธีที่ดีที่สุดที่ฉันพบในการเลียนแบบคือการแทนที่ _ str _ และ _ eq _ เพื่อให้คุณสามารถเปรียบเทียบได้และเมื่อคุณใช้ print() คุณจะได้รับสตริงแทนที่จะเป็นค่าตัวเลข
class enumSeason():
Spring = 0
Summer = 1
Fall = 2
Winter = 3
def __init__(self, Type):
self.value = Type
def __str__(self):
if self.value == enumSeason.Spring:
return 'Spring'
if self.value == enumSeason.Summer:
return 'Summer'
if self.value == enumSeason.Fall:
return 'Fall'
if self.value == enumSeason.Winter:
return 'Winter'
def __eq__(self,y):
return self.value==y.value
การใช้งาน:
>>> s = enumSeason(enumSeason.Spring)
>>> print(s)
Spring
คุณอาจใช้โครงสร้างการสืบทอดได้ แม้ว่ายิ่งฉันเล่นกับสิ่งนี้มากเท่าไหร่ฉันก็รู้สึกสกปรกมากขึ้นเท่านั้น
class AnimalEnum:
@classmethod
def verify(cls, other):
return issubclass(other.__class__, cls)
class Dog(AnimalEnum):
pass
def do_something(thing_that_should_be_an_enum):
if not AnimalEnum.verify(thing_that_should_be_an_enum):
raise OhGodWhy
_unused, Shaded, Shiny, Transparent, Matte = range(5)
- person zekel; 09.12.2010
Shaded, Shiny, Transparent, Matte = range(1, 5)
ได้ หากคุณไม่ชอบให้ _unused
อยู่ที่นั่น
- person Davy8; 30.01.2011
Materials.shinny
ในบันทึกมากกว่า 1
เพราะ 1
บอกฉันน้อยกว่า Materials.shinny
มาก
- person Gewthen; 17.10.2015
enums
อยู่ใน Python ตั้งแต่ 3.4
- person SudoKid; 04.01.2017