如何设置/获取t给定的属性值x.
class Test:
def __init__(self):
self.attr1 = 1
self.attr2 = 2
t = Test()
x = "attr1"
Run Code Online (Sandbox Code Playgroud) 使用Python 3.4我想测试Enum类是否包含具有特定名称的成员.
例:
class Constants(Enum):
One = 1
Two = 2
Three = 3
print(Constants['One'])
print(Constants['Four'])
Run Code Online (Sandbox Code Playgroud)
得到:
Constants.One
File "C:\Python34\lib\enum.py", line 258, in __getitem__
return cls._member_map_[name]
KeyError: 'Four'
Run Code Online (Sandbox Code Playgroud)
我可以抓住KeyError并将异常作为存在的指示,但也许有更优雅的方式?