1. 程式人生 > 實用技巧 >python 常見的特殊方法

python 常見的特殊方法

特殊方法

特殊方法,也稱為魔術方法

特殊方法都是使用__開頭和結尾的

class Foo(object):
    def __call__(self, *args, **kwargs):
        '''構造方法的執行是由建立物件觸發的,物件加括號執行'''
        print('__call__方法執行了')
        return args, kwargs

    def __init__(self):
        '''構造方法,建立例項時候會自動執行,面向物件中非常常用,一般用來封裝各種引數'''
        print('__init__執行了'
) self.data_dict = {'name': 'yanghao', 'age': 23} def __repr__(self): '''如果一個類中定義了__repr__方法,那麼在repr(物件) 時,預設輸出該方法的返回值。''' return '__repr__ 執行了' def __getitem__(self, key): '''獲取值''' return print(self.data_dict[key]) def __setitem__(self, key, value):
'''設定值''' self.data_dict[key] = value return print(self.data_dict) def __delitem__(self, key): '''刪除值''' self.data_dict.pop(key) return print(self.data_dict) def __getattr__(self, item): '''訪問不存在的屬性會呼叫''' print('__getattr__執行了')
def __setattr__(self, key, value): '''設定屬性''' print('__setattr__執行了') self.__dict__.setdefault(key, value) print(self.data_dict) def __delattr__(self, item): '''del obj.key''' print('執行 __delattr__') print(self.__dict__) self.__dict__.pop(item) def __len__(self): '''len''' return len(self.data_dict) def __str__(self): '''如果類中有str方法的話直接列印例項,會輸出str方法中定義的返回內容''' return '__str__執行了' def __del__(self): '''析構方法,當物件在記憶體中被釋放時,自動觸發執行。''' print('__del__釋放') class Aoo(object): def __init__(self): self.x = 1 print('in init function') def __new__(cls, *args, **kwargs): '''new方法和init方法的區別就是,new方法是正在建立例項時候執行,而init方法是建立例項後才執行。''' print('in new function') return object.__new__(Aoo, *args, **kwargs) if __name__ == '__main__': obj = Foo() # ------------------------------ obj() # __call__ print(repr(obj)) a = obj['name'] obj['phone'] = 18577609987 del obj['age'] # ------------------------------- print('-' * 80) # ------------操作物件屬性------------------- getattr(obj, 'dsadasda') # 不存在的屬性時會呼叫該方法,你可返回任何值,當找不到時便返回。 setattr(obj, 'a1', '123') del obj.data_dict # ------------------------------- print('-' * 80) # ------------------------------- print(len(obj())) print(obj) # ------------------------------- a_obj = Aoo() print(a_obj.x)

除了上面部分還有下面這些特殊方法也都是比較實用的

    # __add__(self, other)
    # __sub__(self, other)
    # __mul__(self, other)
    # __matmul__(self, other)
    # __truediv__(self, other)
    # __floordiv__(self, other)
    # __mod__(self, other)
    # __divmod__(self, other)
    # __pow__(self, other[, modulo])
    # __lshift__(self, other)
    # __rshift__(self, other)
    # __and__(self, other)
    # __xor__(self, other)
    # __or__(self, other)

    # __lt__(self, other) 小於 <
    # __le__(self, other) 小於等於 <=
    # __eq__(self, other) 等於 ==
    # __ne__(self, other) 不等於 !=
    # __gt__(self, other) 大於 >
    # __ge__(self, other) 大於等於 >=