将扩展添加到枚举列表中

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

Add extension to List of enums

问题

我有一个枚举数组希望有一种方便的方法直接访问枚举的字符串表示

举个例子我有以下枚举

from enum import Enum

class Countries(Enum):
    CH = "Switzerland"
    DE = "Germany"
    FR = "France"

sel_countries = [Countries.CH, Countries.FR]

现在我想要一个类似`[Countries.CH, Countries.FR].toString()`的方法它会返回`['Switzerland', 'France']`。

我知道我可以使用`[e.value for e in sel_countries]`来获得所需的结果

但是我如何将这样的方法添加到一个[list][1]对象中呢

  [1]: https://docs.python.org/3/tutorial/datastructures.html
英文:

I have an array of enums and would like a convenient method to access the enum string representation directly.

As an example. I have the following enum

from enum import Enum

class Countries(Enum):
    CH = "Switzerland"
    DE = "Germany"
    FR = "France"

sel_countries = [Countries.CH, Countries.FR]

And now, I would like to have a method like [Countries.CH, Countries.FR].toString() that returns ['Switzerland', 'France'].

I know, I could get the desired results using [e.value for e in sel_countries].

But how could I add such a method to a list object?

答案1

得分: 3

要向内置对象添加方法,最简单的方法是创建一个新的子类。在子类化容器类(如listdict)时,最好使用UserListUserDict

from enum import Enum
from collections import UserList

class Countries(Enum):
    CH = "Switzerland"
    DE = "Germany"
    FR = "France"

class EnumList(UserList):
    def to_string(self):
        return EnumList([item.value for item in self])

sel_countries = EnumList([Countries.CH, Countries.FR])

print(sel_countries.to_string())
英文:

To add methods to builtins, the easiest way is to create a new subclass. When subclassing containers such as list and dict it's best to use UserList and UserDict instead.

from enum import Enum
from collections import UserList

class Countries(Enum):
    CH = "Switzerland"
    DE = "Germany"
    FR = "France"

class EnumList(UserList):
    def to_string(self):
        return EnumList([item.value for item in self])

sel_countries = EnumList([Countries.CH, Countries.FR])

print(sel_countries.to_string())

huangapple
  • 本文由 发表于 2023年2月24日 15:40:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/75553775.html
匿名

发表评论

匿名网友

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

确定