在本篇文章裏小編給各位整理了關於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, *args, **kwargs): # real signature unknown
""" Default dir() implementation. """
pass
# 判斷是否相等 equal ,在obj==other時調用。如果重寫了__eq__方法,則會將__hash__方法置爲None
def __eq__(self, *args, **kwargs): # real signature unknown
""" Return self==value. """
pass
# format(obj)是調用,實現如何格式化obj對象爲字符串
def __format__(self, *args, **kwargs): # real signature unknown
""" Default object formatter. """
pass
# getattr(obj,'xxx')、obj.xxx時都會被調用,當屬性存在時,返回值,不存在時報錯(除非重寫__getattr__方法來處理)。
# 另外,hasattr(obj,'xxx')時也會被調用(估計內部執行了getattr方法)
def __getattribute__(self, *args, **kwargs): # real signature unknown
""" Return getattr(self, name). """
pass
# 判斷是否大於等於 greater than or equal,在obj>=other時調用
def __ge__(self, *args, **kwargs): # real signature unknown
""" Return self>=value. """
pass
# 判斷是否大於 greater than,在obj>other時調用
def __gt__(self, *args, **kwargs): # real signature unknown
""" Return self>value. """
pass
# 調用hash(obj)獲取對象的hash值時調用
def __hash__(self, *args, **kwargs): # real signature unknown
""" Return hash(self). """
pass
def __init_subclass__(self, *args, **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, *args, **kwargs): # real signature unknown
""" Return self<=value. """
pass
# 判斷是否小於 less than,在obj<other時調用
def __lt__(self, *args, **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, *args, **kwargs): # real signature unknown
""" Return self!=value. """
pass
def __reduce_ex__(self, *args, **kwargs): # real signature unknown
""" Helper for pickle. """
pass
def __reduce__(self, *args, **kwargs): # real signature unknown
""" Helper for pickle. """
pass
# 如果不重寫__str__,則__repr__負責print(obj)和交互式命令行中輸出obj的信息
# 如果重寫了__str__,則__repr__只負責交互式命令行中輸出obj的信息
def __repr__(self, *args, **kwargs): # real signature unknown
""" Return repr(self). """
pass
# 使用setattr(obj,'xxx',value)、obj.xxx=value是被調用(注意,構造函數初始化屬性也要調用)
def __setattr__(self, *args, **kwargs): # real signature unknown
""" Implement setattr(self, name, value). """
pass
# 獲取對象內存大小
def __sizeof__(self, *args, **kwargs): # real signature unknown
""" Size of object in memory, in bytes. """
pass
# 設置print(obj)打印的信息,默認是對象的內存地址等信息
def __str__(self, *args, **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):
print("__getattribute__ in Foo")
return object.__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, key, 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, key, 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,工作了發現吃了計算機基礎不好的虧,學歷不行這是
沒辦法的事,只能後天彌補,於是在編碼之外開啓了自己的逆襲之路,不斷的學習python核心知識,深入的研習計算機基礎知識,整理好了,我放在我們的Python學習扣qun:250933691,如果你也不甘平庸,那就與我一起在編碼之外,不斷成長吧!
其實這裏不僅有技術,更有那些技術之外的東西,比如,如何做一個精緻的程序員,而不是“屌絲”,程序員本身就是高貴的一種存在啊,難道不是嗎?[點擊加入]想做你自己想成爲高尚人,加油!
@本文來源於公衆號:csdn2299,喜歡可以關注公衆號 程序員學府