英文:
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
要向内置对象添加方法,最简单的方法是创建一个新的子类。在子类化容器类(如list
和dict
)时,最好使用UserList
和UserDict
。
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())
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论