英文:
Is defining classmethods in Enum classes bad practice or not?
问题
我有枚举类:
class Group(StrEnum):
admin = 'admin'
manager = 'manager'
user = 'user'
@classmethod
def get_staff_groups(cls):
return {cls.admin, cls.manager}
@classmethod
def get_user_groups(cls):
return {cls.user}
这样做好吗?
我尝试了上面写的方式。枚举可以包含方法吗?
英文:
I have Enum class:
class Group(StrEnum):
admin = 'admin'
manager = 'manager'
user = 'user'
@classmethod
def get_staff_groups(cls):
return {cls.admin, cls.manager}
@classmethod
def get_user_groups(cls):
return {cls.user}
Is it good practice or not?
I tried like written above. Can Enum contains methods?
答案1
得分: 3
这是有关 Enum 类和普通类之间区别的Python文档链接: https://docs.python.org/3/howto/enum.html#enum-class-differences。其中一些示例甚至包括一个 classmethod
:
class Weekday(Enum):
MONDAY = 1
TUESDAY = 2
WEDNESDAY = 3
THURSDAY = 4
FRIDAY = 5
SATURDAY = 6
SUNDAY = 7
#
@classmethod
def from_date(cls, date):
return cls(date.isoweekday())
你需要问自己的问题基本上是:"我的方法是否符合我的类的目的?" 如果答案是 "是",那么当然可以将该方法包含在类中。
英文:
Here is the Python doc about the differences between Enum classes and normal ones: https://docs.python.org/3/howto/enum.html#enum-class-differences. Some of the given examples even contain a classmethod
:
class Weekday(Enum):
MONDAY = 1
TUESDAY = 2
WEDNESDAY = 3
THURSDAY = 4
FRIDAY = 5
SATURDAY = 6
SUNDAY = 7
#
@classmethod
def from_date(cls, date):
return cls(date.isoweekday())
What you need to ask yourself is, basically, "does my method serve the purpose of my class?" If the answer is "yes", then sure: the class can contain it.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论