1. 程式人生 > >python的__getattr__、__getattribute__、__setattr__

python的__getattr__、__getattribute__、__setattr__

1.__getattr__

如果某個類定義了__getattr__,那麼當該類的例項字典中找不到所要查詢的屬性時,便會呼叫該方法。

class People:
    def __init__(self):
        self.name = 'John'

    def __getattr__(self, item):
        value = 'The value is % s' % item
        setattr(self, item, value)
        return value
data = People()
print(data.__dict__)
print(data.age)
print(data.__dict__)

{'name': 'John'}
The value is age
{'name': 'John', 'age': 'The value is age'}

然後給people類新增新功能

class Chinese(People):
    def __getattr__(self, item):
        print('__getattr__ is %s' % item)
        return super().__getattr__(item)
ch = Chinese()
print(ch.age)
print(ch.age)

__getattr__ is age
The value is age
The value is age

我們使用super().__getattr__()是為了避免無限遞迴.