類的內置方法(魔法方法)

類的內置方法(魔法方法)

凡是在類內部定義,以__ 開頭__ 結尾的方法都是類的的內置方法,也稱爲魔法方法python

類的內置方法,會在某種條件知足下自動觸發code

一、__ init__

在調用類時自動觸發對象

二、__ new__

在 __ init __ 觸發前自動觸發,調用該類是,內部會經過__ new __ 產生一個新的對象遞歸

class Demo:
    # 在__init__觸發前自動觸發
    def __new__(cls, *args, **kwargs):
        print('__new__執行')
        # 內部會經過object產生一個新對象返回來觸發__init__,若是此處未返回新對象,則不會觸發__init__
        return object.__new__(cls, *args, **kwargs)

    def __init__(self):
        print('__init__執行')

obj = Demo()
# __new__執行
# __init__執行

三、__ getattr__

在經過 「 對象 . 屬性 」 獲取對象屬性時,若沒有該屬性時觸發字符串

class Demo:
    # 在經過 「 對象.屬性 」 獲取對象屬性時,若沒有該屬性時觸發
    def __getattr__(self, item):
    	print('__getattr__執行')
    	print(item)
    	# 沒有時默認返回None,能夠設置默認返回值
    	return '設置的默認返回值'

obj = Demo()
print(obj.x)
# __getattr__執行
# x
# 設置的默認返回值

四、__ getattribute__

在經過 「 對象.屬性 」 獲取對象屬性時,無論沒有該屬性,都會觸發get

**注意:當 __ getattr __ 和 __ getattribute __ 同時存在在類內部時,只會觸發 __ getattribute __ **it

class Demo:
    def __getattribute__(self, item):
        print('__getattribute__執行')
        print(item)
        # 無論有沒有都是默認返回None,能夠設置默認返回值
        return '設置的默認返回值'

        # 此處沒法獲取查找的屬性值,不能經過對象.屬性來查找屬性值不然會形成遞歸致使程序崩潰
        # return self.__dict__[item]
        # return getattr(self, item)

obj = Demo()
obj.x = 10
print(obj.x) 
# __getattribute__執行
# x
# 設置的默認返回值

五、__ setattr __

當使用 「 對象 . 屬性 = 屬性值」 時,添加或修改屬性值時觸發class

class Demo:
        # 當使用 對象. 屬性 = 屬性值 時觸發
    def __setattr__(self, key, value):
        print('__setattr__執行')
        print(key,value)
        #須要將添加或修改的屬性加到對象名稱空間中
        self.__dict__[key] = value

obj = Demo()
print(obj.__dict__)  # {}
obj.x = 10  # __setattr__執行/ x 10
print(obj.__dict__)  # {'x': 10}

六、__ call__

在調用對象,「 對象()」時觸發object

class Demo:
    # 使用對象()調用對象時觸發
    def __call__(self, *args, **kwargs):
        print('__call__執行')
        # 默認返回None,能夠設置默認返回值
        return '設置默認值'

obj = Demo()
print(obj())
# __call__執行
# 設置默認值

七、__ str__

在打印對象時觸發,必要要有一個 「 字符串 」 返回值程序

class Demo:
    def __str__(self):
        print('__str__執行')
        # 必需要有一個字符串返回值
        return '字符串'

obj = Demo()
print(obj)
# __str__執行
# 字符串

八、__ getitem__

在經過「 對象[key]」 來獲取屬性值時觸發

class Demo:
    def __getitem__(self, item):
        print('__getitem__執行')
        print(item)
        # 查找到value的值並返回,沒有會報錯,不寫此步無論有沒有都會返回None
        return self.__dict__[item]

obj = Demo()
obj.x = 10
print(obj['x'])
# __getitem__執行
# x
# 10

九、__ setitem__

在經過 「 對象[key] = value 」設置屬性時觸發

class Demo:
    def __setitem__(self, key, value):
        print('__getitem__執行')
        print(key, value)
        # 須要將添加或修改的屬性加到對象名稱空間中
        self.__dict__[key] = value

obj = Demo()
print(obj.__dict__)  #{}
obj['x'] = 10
# __getitem__執行
# x 10
print(obj.__dict__) # {'x': 10}
相關文章
相關標籤/搜索
本站公眾號
   歡迎關注本站公眾號,獲取更多信息