我有一堂课,里面有一个字典。我想通过直接“ instance.key”而不是“ instance.d [key]”来访问字典中的变量。怎么做?
class A:
def __init__(self):
self.a = 1
self.b = 2
self.fields = {'c': 3, 'd': 4}
def main():
a = A()
print(a.a) # 1
print(a.b) # 2
print(a.c) # currently raise Exception, I want it to print 3
print(a.d) # currently raise Exception, I want it to print 4
if __name__ == '__main__':
main()
Run Code Online (Sandbox Code Playgroud)
您可以覆盖object.__getattr__(self, name)方法(可以定义此类方法以自定义类实例的属性访问的含义):
class A:
def __init__(self):
self.a = 1
self.b = 2
self.fields = {'c': 3, 'd': 4}
def __getattr__(self, item):
return self.__dict__.get(item) or self.__dict__['fields'].get(item)
a = A()
print(a.a) # 1
print(a.b) # 2
print(a.c) # 3
print(a.d) # 4
Run Code Online (Sandbox Code Playgroud)
推荐链接: __getattr__
| 归档时间: |
|
| 查看次数: |
28 次 |
| 最近记录: |