Python__getattr__、__setattr__、__delattr__、__getitem__、__setitem__、__getattribute__方法的理解
生活随笔
收集整理的這篇文章主要介紹了
Python__getattr__、__setattr__、__delattr__、__getitem__、__setitem__、__getattribute__方法的理解
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
1. __getattr__(self, item):
在訪問對象的item屬性的時候,如果對象并沒有這個相應的屬性,方法,那么將會調用這個方法來處理。。。這里要注意的時,假如一個對象叫fjs, ?他有一個屬性:fjs.name = "fjs",那么在訪問fjs.name的時候因為當前對象有這個屬性,那么將不會調用__getattr__()方法,而是直接返回了擁有的name屬性了
2. __setattr__(self, item, value):
當試圖對象的item特性賦值的時候將會被調用。
# -*- coding:utf-8 -*- class Student:def __init__(self, work, score):self.work = workself.score = scoredef __getattr__(self, item):return item + ' is not exits'def __setattr__(self, key, value):self.__dict__[key] = value#object.__setattr__(self, key, value) 兩條語句等效def __delattr__(self, name):print("你正在刪除一個屬性")return super().__delattr__(name)def __getitem__(self, item):return self.__dict__[item]def __setitem__(self, key, value):self.__dict__[key] = values = Student() print(s.name) # 調用__getattr__方法 輸出'name is not exits' s.age = 1 # 調用__setattr__ 方法 print(s.age) # 輸出 1 print(s['age']) # 調用 __getitem__方法 輸出1 s['name'] = 'tom' # 調用 __setitem__ 方法 print(s['name']) # 調用 __getitem__ 方法 輸出 'tom'del s.work # 調用__delattr__方法 try:print(s.work) # 輸出 'MyClass' object has no attribute 'work' except AttributeError as reason:print(reason)輸出結果為:
name is not exits 1 1 tom3.?__getattribute__
class C(object):a = 'abc'def __getattribute__(self, *args, **kwargs):print("__getattribute__() is called")return object.__getattribute__(self, *args, **kwargs) # return "haha"def __getattr__(self, name):print("__getattr__() is called ")return name + " from getattr"def __get__(self, instance, owner):print("__get__() is called", instance, owner)return selfdef foo(self, x):print(x)class C2(object):d = C() if __name__ == '__main__':c = C()c2 = C2()print(c.a)print(c.zzzzzzzz)c2.dprint(c2.d.a)?輸出結果
__getattribute__() is called abc __getattribute__() is called __getattr__() is called zzzzzzzz from getattr __get__() is called <__main__.C2 object at 0x16d2310> <class '__main__.C2'> __get__() is called <__main__.C2 object at 0x16d2310> <class '__main__.C2'> __getattribute__() is called abc?
新人創作打卡挑戰賽發博客就能抽獎!定制產品紅包拿不停!總結
以上是生活随笔為你收集整理的Python__getattr__、__setattr__、__delattr__、__getitem__、__setitem__、__getattribute__方法的理解的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: curl命令使用介绍
- 下一篇: Python 的构建工具 setup.p