반응형
파이썬에서 열거 형에 대한 일반적인 관행은 무엇입니까? [복제]
가능한 중복 :
파이썬에서 '열거'를 어떻게 나타낼 수 있습니까?
파이썬에서 열거 형에 대한 일반적인 관행은 무엇입니까? 즉, 어떻게 파이썬에서 복제됩니까?
public enum Materials
{
Shaded,
Shiny,
Transparent,
Matte
}
class Materials:
Shaded, Shiny, Transparent, Matte = range(4)
>>> print Materials.Matte
3
이 패턴을 여러 번 보았습니다.
>>> 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이 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
You could probably use an inheritance structure although the more I played with this the dirtier I felt.
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
참고URL : https://stackoverflow.com/questions/702834/whats-the-common-practice-for-enums-in-python
반응형
'IT' 카테고리의 다른 글
더 작은 경우 UIScrollView의 컨텐츠 중심 (0) | 2020.06.24 |
---|---|
문자열을 QString으로 변경하는 방법은 무엇입니까? (0) | 2020.06.24 |
“com.google.firebase.provider.FirebaseInitProvider”클래스를 찾지 못했습니까? (0) | 2020.06.24 |
HTML5 양식 유효성 검사 기본 오류 메시지를 어떻게 변경하거나 제거 할 수 있습니까? (0) | 2020.06.23 |
각도 컴포넌트와 모듈의 차이점 (0) | 2020.06.23 |