Part of the content comes from the web

If the attribute lookup fails in the instance and the corresponding class (via a dict), the class’s __getattr__ function is called.

If this function is not defined, an AttributeError exception is thrown. Thus, __getattr__ must be the last step in the attribute lookup

Here’s an example:

Class A(object): 2 def init(self, A, b): 3 self.a1 = a 4 self.b1 = b 5 print(‘init’) 6 7 def mydefault(self, *args): 8 print(‘default:’ + str(args[0])) 9 10 def getattr(self, name): 11 print(“other fn:”, name) 12 return self.mydefault 13 14 15 a1 = A(10, 20) 16 a1.fn1(33) 17 a1.fn2(‘hello’)

Init other fn: fn1 default:33 Other fn: fn2 default:hello

Call attribute exceptions can be handled with the __getattr__ method

Class Student(object): def getattr(self, attrname): if attrname == “age”: return ‘age:40’ else: class Student(object): def getattr(self, attrname): if attrname == “age”: return ‘age:40’ else: raise AttributeError(attrname)

X = Student() print(x.age) # 40 print(x.name) print(x.name) When x.name is executed, the __getattr__ method does not handle it and throws an exception

Age :40 File “xxxx. py”, line 10, in print(x.name) File” xxxx. py”, line 6, In getattr raise AttributeError(attrname) AttributeError: name Copy code The following is an example of a classic application of _getattr_ that calls dict key-value pairs

Def init(self, *args, **kwargs): super(args, **kwargs).init(*args, **kwargs)

def __getattr__(self, name):
    value = self[name]
    if isinstance(value, dict):
        value = ObjectDict(value)
    return value
Copy the code

if name == ‘main’: od = ObjectDict(asf = {‘a’: 1}, d = True) print(od.asf, od.asf.a) # {‘a’: 1} 1 print(od.d) # True