I have a class, and there is a dict in it. I want to visit variables in the dict by direct "instance.key" instead of "instance.d[key]". How to do that?
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()
You are able to override object.__getattr__(self, name)
method (such methods can be defined to customize the meaning of attribute access for class instances):
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
Referece link: __getattr__