[Python之路] object類中的特殊方法

1、object類的源碼

python版本:3.8python

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__ = ''

2、經常使用特殊方法解釋

1.__getattribute__方法

1)何時被調用

這個特殊方法是在咱們使用類的對象進行obj.屬性名getattr(obj,屬性名)來取對象屬性的值的時候被調用。例如:less

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。ssh

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

2)與__getattr__的區別

咱們在類的實現中,能夠重寫__getattr__方法,那麼__getattr__方法和__getattribute__方法有什麼區別??函數

咱們知道__getattribute__方法無論屬性是否存在,都會被調用。而__getattr__只在屬性不存在時調用,默認會拋出 AttributeError: 'Foo' object has no attribute 'age' 這樣的錯誤,但咱們能夠對其進行重寫,作咱們須要的操做:this

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。

返回結果:spa

__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,屬性名,屬性值),即爲屬性賦值時被調用。code

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賦值就沒法工做了。orm

特別注意,在類的構造函數中對屬性進行初始化賦值時也是調用了該方法:

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

 

 

 

 

###

相關文章
相關標籤/搜索