?? ?? ??
?? ????? Python?? ?? ?? ??? ????. ??? Python ???? ???? ??? ????? ????. ??? ??? Python? ?? ??? ??? ?? ????? ??? ??? get ???? set ???? ??? ? ??? ????. Python? ??? ?? ???? ?? ???? ??? ? ????.
Method | Description |
__getattr__(self, name) | ? ???? ???? ?? ??? ?????? ? ?? ??? ?????. ??? ? ???? ?????? ??? ??? ?? ??????? ? ?? ???? ?? ?? ??? ?? ??? ? ????. |
__setattr__(self, name, value) | ? ??? ???? ??? ?? ??? ?????. ??? ??? ????? ??? ???? ??? ?? ??? ?????. ? ?? ??? ?? __setattr__? ??? ? "?? ??" ??, |
__delattr__(self, name) | ? ??? ??? ????. __delattr__ ? _ _setattr__? ??? ??? ?? ??? ????? ?? ???? ?? ?????. __delattr__? ???? ?? ??? "?? ??" ??? ???? ???? |
__getattribute__(self, name) | __getattribute__? ??? ???? ?? ??? ?????. ?? ?? __getattr__? ??? ???? ?? ???? ??????. . ??. ??? __getattribute__? ???? Python ????? "?? ??" ??? ????? __getattr__? ???? ?? __getattribute__``__getattribute__? ???? ???. |
? ??? ??? ? ? ??? ?? ?? ??? ??? ? ?? ??? ??? ? ???, ?? ??? ?? ? ? ????.
def __setattr__(self, name, value): self.name = value # 每當(dāng)屬性被賦值的時候, ``__setattr__()`` 會被調(diào)用,這樣就造成了遞歸調(diào)用。 # 這意味這會調(diào)用 ``self.__setattr__('name', value)`` ,每次方法會調(diào)用自己。這樣會造成程序崩潰。 def __setattr__(self, name, value): # 給類中的屬性名分配值 self.__dict__[name] = value # 定制特有屬性
? ???? ???? ???? ??? ??? ????. ??:
#!/usr/bin/env python3 # -*- coding: UTF-8 -*- class User(object): def __getattr__(self, name): print('調(diào)用了 __getattr__ 方法') return super(User, self).__getattr__(name) def __setattr__(self, name, value): print('調(diào)用了 __setattr__ 方法') return super(User, self).__setattr__(name, value) def __delattr__(self, name): print('調(diào)用了 __delattr__ 方法') return super(User, self).__delattr__(name) def __getattribute__(self, name): print('調(diào)用了 __getattribute__ 方法') return super(User, self).__getattribute__(name) if __name__ == '__main__': user = User() # 設(shè)置屬性值,會調(diào)用 __setattr__ user.attr1 = True # 屬性存在,只有__getattribute__調(diào)用 user.attr1 try: # 屬性不存在, 先調(diào)用__getattribute__, 后調(diào)用__getattr__ user.attr2 except AttributeError: pass # __delattr__調(diào)用 del user.attr1
?? ??:
調(diào)用了 __setattr__ 方法 調(diào)用了 __getattribute__ 方法 調(diào)用了 __getattribute__ 方法 調(diào)用了 __getattr__ 方法 調(diào)用了 __delattr__ 方法