在Enum类中定义classmethod是否是不良做法?

huangapple go评论70阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2023年5月31日 23:08:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/76374942.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定