1. 程式人生 > 程式設計 >Python object類中的特殊方法程式碼講解

Python object類中的特殊方法程式碼講解

python版本:3.8

class object:
 """ The most base type """

 # del obj.xxx或delattr(obj,'xxx')時被呼叫,刪除物件中的一個屬性
 def __delattr__(self,*args,**kwargs): # real signature unknown
 """ Implement delattr(self,name). """
 pass

 # 對應dir(obj),返回一個列表,其中包含所有屬性和方法名(包含特殊方法)
 def __dir__(self,**kwargs): # real signature unknown
 """ Default dir() implementation. """
 pass

 # 判斷是否相等 equal ,在obj==other時呼叫。如果重寫了__eq__方法,則會將__hash__方法置為None
 def __eq__(self,**kwargs): # real signature unknown
 """ Return self==value. """
 pass

 # format(obj)是呼叫,實現如何格式化obj物件為字串
 def __format__(self,**kwargs): # real signature unknown
 """ Default object formatter. """
 pass

 # getattr(obj,'xxx')、obj.xxx時都會被呼叫,當屬性存在時,返回值,不存在時報錯(除非重寫__getattr__方法來處理)。
 # 另外,hasattr(obj,'xxx')時也會被呼叫(估計內部執行了getattr方法)
 def __getattribute__(self,**kwargs): # real signature unknown
 """ Return getattr(self,name). """
 pass

 # 判斷是否大於等於 greater than or equal,在obj>=other時呼叫
 def __ge__(self,**kwargs): # real signature unknown
 """ Return self>=value. """
 pass

 # 判斷是否大於 greater than,在obj>other時呼叫
 def __gt__(self,**kwargs): # real signature unknown
 """ Return self>value. """
 pass

 # 呼叫hash(obj)獲取物件的hash值時呼叫
 def __hash__(self,**kwargs): # real signature unknown
 """ Return hash(self). """
 pass

 def __init_subclass__(self,**kwargs): # real signature unknown
 """
 This method is called when a class is subclassed.

 The default implementation does nothing. It may be
 overridden to extend subclasses.
 """
 pass

 # object建構函式,當子類沒有建構函式時,會呼叫object的__init__建構函式
 def __init__(self): # known special case of object.__init__
 """ Initialize self. See help(type(self)) for accurate signature. """
 pass

 # 判斷是否小於等於 less than or equal,在obj<=other時呼叫
 def __le__(self,**kwargs): # real signature unknown
 """ Return self<=value. """
 pass

 # 判斷是否小於 less than,在obj<other時呼叫
 def __lt__(self,**kwargs): # real signature unknown
 """ Return self<value. """
 pass

 # 建立一個cls類的物件,並返回
 @staticmethod # known case of __new__
 def __new__(cls,*more): # known special case of object.__new__
 """ Create and return a new object. See help(type) for accurate signature. """
 pass

 # 判斷是否不等於 not equal,在obj!=other時呼叫
 def __ne__(self,**kwargs): # real signature unknown
 """ Return self!=value. """
 pass

 def __reduce_ex__(self,**kwargs): # real signature unknown
 """ Helper for pickle. """
 pass

 def __reduce__(self,**kwargs): # real signature unknown
 """ Helper for pickle. """
 pass

 # 如果不重寫__str__,則__repr__負責print(obj)和互動式命令列中輸出obj的資訊
 # 如果重寫了__str__,則__repr__只負責互動式命令列中輸出obj的資訊
 def __repr__(self,**kwargs): # real signature unknown
 """ Return repr(self). """
 pass

 # 使用setattr(obj,'xxx',value)、obj.xxx=value是被呼叫(注意,建構函式初始化屬性也要呼叫)
 def __setattr__(self,**kwargs): # real signature unknown
 """ Implement setattr(self,name,value). """
 pass

 # 獲取物件記憶體大小
 def __sizeof__(self,**kwargs): # real signature unknown
 """ Size of object in memory,in bytes. """
 pass

 # 設定print(obj)列印的資訊,預設是物件的記憶體地址等資訊
 def __str__(self,**kwargs): # real signature unknown
 """ Return str(self). """
 pass

 @classmethod # known case
 def __subclasshook__(cls,subclass): # known special case of object.__subclasshook__
 """
 Abstract classes can override this to customize issubclass().

 This is invoked early on by abc.ABCMeta.__subclasscheck__().
 It should return True,False or NotImplemented. If it returns
 NotImplemented,the normal algorithm is used. Otherwise,it
 overrides the normal algorithm (and the outcome is cached).
 """
 pass
 # 某個物件是由什麼類建立的,如果是object,則是type類<class 'type'>
 __class__ = None
 # 將物件中所有的屬性放入一個字典,例如{'name':'Leo','age':32}
 __dict__ = {}
 # 類的doc資訊
 __doc__ = ''
 # 類屬於的模組,如果是在當前執行模組,則是__main__,如果是被匯入,則是模組名(即py檔名去掉.py)
 __module__ = ''

二、常用特殊方法解釋

1.__getattribute__方法

1)什麼時候被呼叫

這個特殊方法是在我們使用類的物件進行obj.屬性名或getattr(obj,屬性名)來取物件屬性的值的時候被呼叫。例如:

class Foo(object):
 def __init__(self):
 self.name = 'Alex'

 def __getattribute__(self,item):
 print("__getattribute__ in Foo")
 return object.__getattribute__(self,item)


if __name__ == '__main__':
 f = Foo()
 print(f.name) # name屬性存在 或者 getattr(f,name)
 print(f.age) # age屬性不存在

不管屬性是否存在,__getattribute__方法都會被呼叫。如果屬性存在,則返回該屬性的值,如果屬性不存在,則返回None。

注意,我們在使用hasattr(obj,屬性名)來判斷某個屬性是否存在時,__getattribute__方法也會被呼叫。

2)與__getattr__的區別

我們在類的實現中,可以重寫__getattr__方法,那麼__getattr__方法和__getattribute__方法有什麼區別?

我們知道__getattribute__方法不管屬性是否存在,都會被呼叫。而__getattr__只在屬性不存在時呼叫,預設會丟擲 AttributeError: 'Foo' object has no attribute 'age' 這樣的錯誤,但我們可以對其進行重寫,做我們需要的操作:

class Foo(object):
 def __init__(self):
 self.name = 'Alex'

 def __getattribute__(self,item)

 def __getattr__(self,item):
 print("%s不存在,但我可以返回一個值" % item)
 return 54


if __name__ == '__main__':
 f = Foo()
 print(f.name) # name屬性存在
 print(f.age) # age屬性不存在,但__getattr__方法返回了54,所以這裡列印54。

返回結果:

__getattribute__ in Foo
Alex
__getattribute__ in Foo
age不存在,但我可以返回一個值
54

我們看到,f.name和f.age都呼叫了__getattribute__方法,但是隻有f.age時呼叫了__getattr__方法。所以,我們可以利用__getattr__做很多事情,例如從類中的一個字典中取值,或者處理異常等。

2.__setattr__方法

當我們執行obj.name='alex'或setattr(obj,屬性名,屬性值),即為屬性賦值時被呼叫。

class Foo(object):
 def __init__(self):
  self.name = 'Alex'

 # obj.xxx = value時呼叫
 def __setattr__(self,key,value):
  print('setattr')
  return object.__setattr__(self,value)


if __name__ == '__main__':
 f = Foo()
 f.name = 'Jone' # 列印setattr
 print(f.name)

如果__setattr__被重寫(不呼叫父類__setattr__的話)。則使用obj.xxx=value賦值就無法工作了。

特別注意,在類的建構函式中對屬性進行初始化賦值時也是呼叫了該方法:

class Foo(object):
 def __init__(self):
  self.name = 'Alex' # 這裡也要呼叫__setattr__
  ...

當我們需要重寫__setattr__方法的時候,就要注意初始化時要使用object類的__setattr__來初始化:

class Local(object):
 def __init__(self):
  # 這裡不能直接使用self.DIC={},因為__setattr__被重寫了
  object.__setattr__(self,'DIC',{})

 def __setattr__(self,value):
  self.DIC[key] = value

 def __getattr__(self,item):
  return self.DIC.get(item,None)


if __name__ == '__main__':
 obj = Local()
 obj.name = 'Alex' # 向DIC字典中存入值
 print(obj.name) # 從DIC字典中取出值

3.__delattr__方法

這個方法對應del obj.屬性名和delattr(obj,屬性名)兩種操作時被呼叫。即,刪除物件中的某個屬性。

if hasattr(f,'xxx'): # 判斷f物件中是否存在屬性xxx
 delattr(f,'xxx') # 如果存在則刪除。當xxx不存在時刪除會報錯
 # del f.xxx # 同上

4.__dir__方法

對應dir(obj)獲取物件中所有的屬性名,包括所有的屬性和方法名。

f = Foo()
print(f.__dir__()) # ['name','__module__','__init__','__setattr__','__getattribute__','__dir__','__dict__','__weakref__','__doc__','__repr__','__hash__','__str__','__delattr__','__lt__','__le__','__eq__','__ne__','__gt__','__ge__','__new__','__reduce_ex__','__reduce__','__subclasshook__','__init_subclass__','__format__','__sizeof__','__class__']

返回一個列表。

5.__eq__和__hash__

__eq__是判斷obj==other的時候呼叫的,預設呼叫的是object繼承下去的__eq__。

f1 = Foo()
f2 = f1
print(f1 == f2) # True
print(f1 is f2) # True
print(hash(f1) == hash(f2)) # True

預設情況下,f1 == f2,f1 is f2,hash(f1)==hash(f2)都應該同時為True(或不相等,同為False)。

如果我們重寫了__eq__方法,例如兩個物件的比較變成比較其中的一個屬性:

class Foo(object):
 def __init__(self):
  self.name = 'Alex' # 這裡也要呼叫__
  self.ccc = object.__class__
 def __eq__(self,other):
  return self.name==other.name

即,如果self.name==other.name,則認為物件相等。

f1 = Foo()
f2 = Foo()
print(f1 == f2) # True
print(f1 is f2) # False
print(hash(f1) == hash(f2)) # 丟擲異常TypeError錯誤

為什麼hash會丟擲異常,這是因為如果我們在某個類中重寫了__eq__方法,則預設會將__hash__=None。所以,當我們呼叫hash(obj)時,__hash__方法無法執行。

總結:

當我們實現的類想成為不可hash的類,則可以重寫__eq__方法,然後不重寫__hash__,__hash__方法會被置None,該類的物件就不可hash了。

預設提供的__hash__方法(hash(obj))對於值相同的變數(型別有限制,有些型別不能hash,例如List),同直譯器下hash值相同,而不同直譯器下hash值不同。所以,如果我們想要hash一個目標,應該使用hashlib模組。

hash和id的區別,理論上值相同的兩個物件hash值應該相同,而id可能不同(必須是同一個物件,即記憶體地址相同,id才相同。id(obj)是obj的唯一標識。)

6.__gt__、__lt__、__ge__、__le__

這幾個都是用於比較大小的,我們可以對其進行重寫,來自定義物件如何比較大小(例如只比較物件中其中一個屬性的值)。

7.__str__和__repr__

__str__用於定義print(obj)時列印的內容。

class Foo(object):
 def __init__(self):
  self.name = 'Alex'

 def __str__(self):
  return "我是Foo"


if __name__ == '__main__':
 f1 = Foo()
 print(f1) # 列印 我是Foo

在命令列下:

>>> class Foo(object):
...  def __str__(self):
...    return "我是Foo"
...
>>> f1 = Foo()
>>> print(f1)
我是Foo
>>> f1
<__main__.Foo object at 0x0000023BF701C550>

可以看到,使用__str__的話,print可以列印我們指定的值,而命令列輸出則是物件的記憶體地址。

__repr__用於同時定義python命令列輸出obj的內容,以及print(obj)的列印內容(前提是沒有重寫__str__)。

class Foo(object):
 def __init__(self):
  self.name = 'Alex'

 def __repr__(self):
  return "我是Foo"


if __name__ == '__main__':
 f1 = Foo()
 print(f1) # 列印 我是Foo

在命令列下:

>>> class Foo(object):
...  def __repr__(self):
...    return "我是Foo"
...
>>> f1 = Foo()
>>> print(f1)
我是Foo
>>> f1
我是Foo

可以看到,我們只重寫了__repr__,但是print和直接輸出都列印了我們指定的值。

當我們同時重寫__str__和__repr__時:

>>> class Foo():
...  def __str__(self):
...    return "我是Foo---str"
...  def __repr__(self):
...    return "我是Foo---repr"
...
>>> f1 = Foo()
>>> print(f1)
我是Foo---str
>>> f1
我是Foo---repr

可以看到,在同時重寫兩個方法時,__str__負責print的資訊,而__repr__負責命令列直接輸出的資訊。

8.__new__方法

9.__sizeof__方法

10.__class__、__dict__、__module__、__doc__屬性

__class__:返回該生成該物件的類

print(f1.__class__) # <class '__main__.Foo'>

__dict__:返回該物件的所有屬性組成的字典

print(f1.__dict__) # {'name': 'Alex'} 只有一個屬性name

__module__:返回該物件所處模組

class Foo(object):
 def __init__(self):
  self.name = 'Alex'


if __name__ == '__main__':
 f1 = Foo()
 print(f1.__module__) # 列印__main__

如果該物件對應的類在當前執行的模組,則列印__main__。

import test3

f = test3.Foo()
print(f.__module__) # 列印test3

如果物件對應的類在其他模組,則列印模組名。

__doc__:類的註釋

class Foo(object):
 """
 這是一個類,名叫Foo
 """
 def __init__(self):
  self.name = 'Alex'


if __name__ == '__main__':
 f1 = Foo()
 print(f1.__doc__) # 列印 這是一個類,名叫Foo

到此這篇關於Python object類中的特殊方法程式碼講解的文章就介紹到這了,更多相關Python object類中的特殊方法內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!