Python常用特殊方法實例總結(jié)
本文實例講述了Python常用特殊方法。分享給大家供大家參考,具體如下:
1 __init__和__new__
__init__
方法用來初始化類實例;__new__
方法用來創(chuàng)建類實例。
主要的區(qū)別:
1).__init__通常用于初始化一個新實例,控制初始化的過程,發(fā)生在類實例被創(chuàng)建完以后。它是實例級別的方法。
2).__new__通常用于控制生成一個新實例的過程。它是類級別的方法。
__new__具體的作用:
1) 繼承一些不可變的class時(比如int, str, tuple),提供一個自定義這些類的實例化過程的途徑
2) 實現(xiàn)自定義的metaclass
例子:實現(xiàn)永遠返回正數(shù)
class PositiveInteger(int): #繼承類int def __new__(cls, value): return super().__new__(cls, abs(value)) #返回父類的__new__方法 i = PositiveInteger(-3) #類實例化 print(i) 3
注意點:
關(guān)于__init__
方法:第一個參數(shù)必須是self
;無返回值
關(guān)于__new__
方法:
1) 繼承自object的新式類才有__new__
2) __new__
至少要有一個參數(shù)cls,代表要實例化的類,此參數(shù)在實例化時由Python解釋器自動提供
3) __new__
必須要有返回值,返回實例化出來的實例(也就是__init__
的self
),可以返回父類__new__
出來的實例,或者直接是object的__new__
出來的實例
2 __del__方法
當對象所有的引用都被刪除后觸發(fā)該方法,代碼如下:
class Testdel(): def __del__(self): print("using __del__") t = Testdel() t1 = t del t1 del t using __del__
3 __str__和__repr__
__repr__
和__str__
這兩個方法都是用于顯示的,__str__
是面向用戶的,而__repr__
面向程序員
定義__repr__
的簡單方法:定義了__str__
之后,賦值給__repr__
,如下:
__repr__ = __str__
4 屬性訪問
__getattr__(self, name)
:當用戶試圖獲取一個不存在的屬性(name)時的行為
__getattribute__(self, name)
:當類的屬性被訪問時的行為
__setattr__(self, name, value)
:當一個屬性被設(shè)置時的行為
__delattr__(self, name)
:當一個屬性被刪除時的行為
死循環(huán)陷阱:
class Rectangle: def __init__(self, width=0, height=0): self.width = width self.height = height def __setattr__(self, name, value): if name == ‘square': self.width = value self.height = value else: self.name = value def getArea(self): return self.width * self.height r = Rectangle(3,4)
實例化r = Rectangle(3, 4)
就會出現(xiàn)死循環(huán),因為在__init__
里面出現(xiàn)了設(shè)置屬性值,跳到__setattr__
里面e的self.name = value
這一句,也就是繼續(xù)賦值操作self.width = width
,所以進入死循環(huán)。解決方法:
1) else子句改為:super().__setattr__(name, value)
2) else子句改為:self.__dict__[name] = value
5 描述符:將某種特殊類型的類的實例指派給另一個類的屬性
特殊類型是指:
__get__(self, instance, owner)
:訪問屬性,返回屬性的值
__set__(self, instance, value)
:用于設(shè)置屬性,不返回任何內(nèi)容
__delete__(self, instance)
:刪除屬性,不返回任何內(nèi)容
self
:描述符類本身的實例,instance
:擁有者類的實例,owner
:擁有者,類本身
class MyDecriptor: def __get__(self, instance, owner): #理解self instance owner的含義 print(‘getting...', self, instance, owner) def __set__(self, instance, value): print(‘setting…',self, instance,value) def __delete__(self, instance): print(‘deleting…',self, instance) class Test: x = MyDecriptor() test = Test() #實例化 test.x test.x = ‘X-man' del test.x
關(guān)于Python相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Python面向?qū)ο蟪绦蛟O(shè)計入門與進階教程》、《Python數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Python函數(shù)使用技巧總結(jié)》、《Python字符串操作技巧匯總》、《Python編碼操作技巧總結(jié)》及《Python入門與進階經(jīng)典教程》
希望本文所述對大家Python程序設(shè)計有所幫助。
相關(guān)文章
pytorch中torch.stack()函數(shù)用法解讀
這篇文章主要介紹了pytorch中torch.stack()函數(shù)用法,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-04-04scrapy框架中用ssh連接遠程服務(wù)器的實現(xiàn)
本文主要介紹了scrapy?框架中用ssh連接遠程服務(wù)器的實現(xiàn),文中通過示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2022-01-01python數(shù)據(jù)結(jié)構(gòu)之遞歸方法講解
這篇文章主要介紹了python數(shù)據(jù)結(jié)構(gòu)之遞歸講解,遞歸是解決問題的一種方法,它將問題不斷地分成更小的子問題,直到子問題可以用普通的方法解決。通常情況下,遞歸會使用一個不停調(diào)用自己的函數(shù),下面來看看文章對此的詳細介紹吧2021-12-12pandas報錯AttributeError: DataFrame object has&
這篇文章主要介紹了pandas報錯AttributeError: DataFrame object has no attribute ix問題及解決,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-02-02