介紹Python的魔術方法 - Magic Method

前言

在Python中,全部以__雙下劃線包起來的方法,都統稱爲"魔術方法"。好比咱們接觸最多的__init__.html

有些魔術方法,咱們可能之後一生都不會再遇到了,這裏也就只是簡單介紹下;python

而有些魔術方法,巧妙使用它能夠構造出很是優美的代碼,好比將複雜的邏輯封裝成簡單的API。git

本文編輯的思路借鑑自Rafe Kettler的這篇博客: A Guide to Python Magic Methods,並補充了一些代碼示例。github

介紹的順序大概是:常見的先介紹,越少見的越靠後講。編程

本文中用到的代碼示例,能夠在個人github下載到。segmentfault

構造和初始化

__init__咱們很熟悉了,它在對象初始化的時候調用,咱們通常將它理解爲"構造函數".數組

實際上, 當咱們調用x = SomeClass()的時候調用,__init__並非第一個執行的, __new__纔是。因此準確來講,是__new____init__共同構成了"構造函數".數據結構

__new__是用來建立類並返回這個類的實例, 而__init__只是將傳入的參數來初始化該實例.app

__new__在建立一個實例的過程當中一定會被調用,但__init__就不必定,好比經過pickle.load的方式反序列化一個實例時就不會調用__init__socket

__new__方法老是須要返回該類的一個實例,而__init__不能返回除了None的任何值。好比下面例子:

class Foo(object):

    def __init__(self):
        print 'foo __init__'
        return None  # 必須返回None,不然拋TypeError

    def __del__(self):
        print 'foo __del__'

實際中,你不多會用到__new__,除非你但願可以控制類的建立。
若是要講解__new__,每每須要牽扯到metaclass(元類)的介紹。
若是你有興趣深刻,能夠參考個人另外一篇博客: 理解Python的metaclass

對於__new__的重載,Python文檔中也有了詳細的介紹。

在對象的生命週期結束時, __del__會被調用,能夠將__del__理解爲"析構函數".
__del__定義的是當一個對象進行垃圾回收時候的行爲。

有一點容易被人誤解, 實際上,x.__del__() 並非對於del x的實現,可是每每執行del x時會調用x.__del__().

怎麼來理解這句話呢? 繼續用上面的Foo類的代碼爲例:

foo = Foo()
foo.__del__()
print foo
del foo
print foo  # NameError, foo is not defined

若是調用了foo.__del__(),對象自己仍然存在. 可是調用了del foo, 就再也沒有foo這個對象了.

請注意,若是解釋器退出的時候對象還存在,就不能保證 __del__ 被確切的執行了。因此__del__並不能替代良好的編程習慣。
好比,在處理socket時,及時關閉結束的鏈接。

屬性訪問控制

總有人要吐槽Python缺乏對於類的封裝,好比但願Python可以定義私有屬性,而後提供公共可訪問的getter和 setter。Python其實能夠經過魔術方法來實現封裝。

__getattr__(self, name)

該方法定義了你試圖訪問一個不存在的屬性時的行爲。所以,重載該方法能夠實現捕獲錯誤拼寫而後進行重定向, 或者對一些廢棄的屬性進行警告。

__setattr__(self, name, value)

__setattr__ 是實現封裝的解決方案,它定義了你對屬性進行賦值和修改操做時的行爲。
無論對象的某個屬性是否存在,它都容許你爲該屬性進行賦值,所以你能夠爲屬性的值進行自定義操做。有一點須要注意,實現__setattr__時要避免"無限遞歸"的錯誤,下面的代碼示例中會提到。

__delattr__(self, name)

__delattr____setattr__很像,只是它定義的是你刪除屬性時的行爲。實現__delattr__是同時要避免"無限遞歸"的錯誤。

__getattribute__(self, name)

__getattribute__定義了你的屬性被訪問時的行爲,相比較,__getattr__只有該屬性不存在時纔會起做用。
所以,在支持__getattribute__的Python版本,調用__getattr__前一定會調用 __getattribute____getattribute__一樣要避免"無限遞歸"的錯誤。
須要提醒的是,最好不要嘗試去實現__getattribute__,由於不多見到這種作法,並且很容易出bug。

例子說明__setattr__的無限遞歸錯誤:

def __setattr__(self, name, value):
    self.name = value
    # 每一次屬性賦值時, __setattr__都會被調用,所以不斷調用自身致使無限遞歸了。

所以正確的寫法應該是:

def __setattr__(self, name, value):
    self.__dict__[name] = value

__delattr__若是在其實現中出現del self.name 這樣的代碼也會出現"無限遞歸"錯誤,這是同樣的緣由。

下面的例子很好的說明了上面介紹的4個魔術方法的調用狀況:

class Access(object):

    def __getattr__(self, name):
        print '__getattr__'
        return super(Access, self).__getattr__(name)

    def __setattr__(self, name, value):
        print '__setattr__'
        return super(Access, self).__setattr__(name, value)

    def __delattr__(self, name):
        print '__delattr__'
        return super(Access, self).__delattr__(name)

    def __getattribute__(self, name):
        print '__getattribute__'
        return super(Access, self).__getattribute__(name)

access = Access()
access.attr1 = True  # __setattr__調用
access.attr1  # 屬性存在,只有__getattribute__調用
try:
    access.attr2  # 屬性不存在, 先調用__getattribute__, 後調用__getattr__
except AttributeError:
    pass
del access.attr1  # __delattr__調用

描述器對象

咱們從一個例子來入手,介紹什麼是描述符,並介紹__get__, __set__, __delete__ 的使用。(放在這裏介紹是爲了跟上一小節介紹的魔術方法做對比)

咱們知道,距離既能夠用單位"米"表示,也能夠用單位"英尺"表示。
如今咱們定義一個類來表示距離,它有兩個屬性: 米和英尺。

class Meter(object):
    '''Descriptor for a meter.'''
    def __init__(self, value=0.0):
        self.value = float(value)
    def __get__(self, instance, owner):
        return self.value
    def __set__(self, instance, value):
        self.value = float(value)

class Foot(object):
    '''Descriptor for a foot.'''
    def __get__(self, instance, owner):
        return instance.meter * 3.2808
    def __set__(self, instance, value):
        instance.meter = float(value) / 3.2808

class Distance(object):
    meter = Meter()
    foot = Foot()

d = Distance()
print d.meter, d.foot  # 0.0, 0.0
d.meter = 1
print d.meter, d.foot  # 1.0 3.2808
d.meter = 2
print d.meter, d.foot  # 2.0 6.5616

在上面例子中,在尚未對Distance的實例賦值前, 咱們認爲meter和foot應該是各自類的實例對象, 可是輸出倒是數值。這是由於__get__發揮了做用.

咱們只是修改了meter,而且將其賦值成爲int,但foot也修改了。這是__set__發揮了做用.

描述器對象(Meter、Foot)不能獨立存在, 它須要被另外一個全部者類(Distance)所持有。
描述器對象能夠訪問到其擁有者實例的屬性,好比例子中Foot的instance.meter

在面向對象編程時,若是一個類的屬性有相互依賴的關係時,使用描述器來編寫代碼能夠很巧妙的組織邏輯。
在Django的ORM中, models.Model中的IntegerField等, 就是經過描述器來實現功能的。

一個類要成爲描述器,必須實現__get__, __set__, __delete__ 中的至少一個方法。下面簡單介紹下:

__get__(self, instance, owner)

參數instance是擁有者類的實例。參數owner是擁有者類自己。__get__在其擁有者對其讀值的時候調用。

__set__(self, instance, value)

__set__在其擁有者對其進行修改值的時候調用。

__delete__(self, instance)

__delete__在其擁有者對其進行刪除的時候調用。

構造自定義容器(Container)

在Python中,常見的容器類型有: dict, tuple, list, string。
其中tuple, string是不可變容器,dict, list是可變容器。
可變容器和不可變容器的區別在於,不可變容器一旦賦值後,不可對其中的某個元素進行修改。
好比定義了l = [1, 2, 3]t = (1, 2, 3)後, 執行l[0] = 0是能夠的,但執行t[0] = 0則會報錯。

若是咱們要自定義一些數據結構,使之可以跟以上的容器類型表現同樣,那就須要去實現某些協議。

這裏的協議跟其餘語言中所謂的"接口"概念很像,同樣的須要你去實現才行,只不過沒那麼正式而已。

若是要自定義不可變容器類型,只須要定義__len____getitem__方法;
若是要自定義可變容器類型,還須要在不可變容器類型的基礎上增長定義__setitem____delitem__
若是你但願你的自定義數據結構還支持"可迭代", 那就還須要定義__iter__

__len__(self)

須要返回數值類型,以表示容器的長度。該方法在可變容器和不可變容器中必須實現。

__getitem__(self, key)

當你執行self[key]的時候,調用的就是該方法。該方法在可變容器和不可變容器中也都必須實現。
調用的時候,若是key的類型錯誤,該方法應該拋出TypeError;
若是無法返回key對應的數值時,該方法應該拋出ValueError。

__setitem__(self, key, value)

當你執行self[key] = value時,調用的是該方法。

__delitem__(self, key)

當你執行del self[key]的時候,調用的是該方法。

__iter__(self)

該方法須要返回一個迭代器(iterator)。當你執行for x in container: 或者使用iter(container)時,該方法被調用。

__reversed__(self)

若是想要該數據結構被內建函數reversed()支持,就還須要實現該方法。

__contains__(self, item)

若是定義了該方法,那麼在執行item in container 或者 item not in container時該方法就會被調用。
若是沒有定義,那麼Python會迭代容器中的元素來一個一個比較,從而決定返回True或者False。

__missing__(self, key)

dict字典類型會有該方法,它定義了key若是在容器中找不到時觸發的行爲。
好比d = {'a': 1}, 當你執行d[notexist]時,d.__missing__('notexist')就會被調用。

下面舉例,使用上面講的魔術方法來實現Haskell語言中的一個數據結構。

# -*- coding: utf-8 -*-
class FunctionalList:
    ''' 實現了內置類型list的功能,並豐富了一些其餘方法: head, tail, init, last, drop, take'''

    def __init__(self, values=None):
        if values is None:
            self.values = []
        else:
            self.values = values

    def __len__(self):
        return len(self.values)

    def __getitem__(self, key):
        return self.values[key]

    def __setitem__(self, key, value):
        self.values[key] = value

    def __delitem__(self, key):
        del self.values[key]

    def __iter__(self):
        return iter(self.values)

    def __reversed__(self):
        return FunctionalList(reversed(self.values))

    def append(self, value):
        self.values.append(value)
    def head(self):
        # 獲取第一個元素
        return self.values[0]
    def tail(self):
        # 獲取第一個元素以後的全部元素
        return self.values[1:]
    def init(self):
        # 獲取最後一個元素以前的全部元素
        return self.values[:-1]
    def last(self):
        # 獲取最後一個元素
        return self.values[-1]
    def drop(self, n):
        # 獲取全部元素,除了前N個
        return self.values[n:]
    def take(self, n):
        # 獲取前N個元素
        return self.values[:n]

咱們再舉個例子,實現Perl語言的AutoVivification,它會在你每次引用一個值未定義的屬性時爲你自動建立數組或者字典。

class AutoVivification(dict):
    """Implementation of perl's autovivification feature."""
    def __missing__(self, key):
        value = self[key] = type(self)()
        return value

weather = AutoVivification()
weather['china']['guangdong']['shenzhen'] = 'sunny'
weather['china']['hubei']['wuhan'] = 'windy'
weather['USA']['California']['Los Angeles'] = 'sunny'
print weather

# 結果輸出:{'china': {'hubei': {'wuhan': 'windy'}, 'guangdong': {'shenzhen': 'sunny'}}, 'USA':    {'California': {'Los Angeles': 'sunny'}}}

在Python中,關於自定義容器的實現還有更多實用的例子,但只有不多一部分可以集成在Python標準庫中,好比Counter, OrderedDict等

上下文管理

with聲明是從Python2.5開始引進的關鍵詞。你應該遇過這樣子的代碼:

with open('foo.txt') as bar:
    # do something with bar

在with聲明的代碼段中,咱們能夠作一些對象的開始操做和清除操做,還能對異常進行處理。
這須要實現兩個魔術方法: __enter____exit__

__enter__(self)

__enter__會返回一個值,並賦值給as關鍵詞以後的變量。在這裏,你能夠定義代碼段開始的一些操做。

__exit__(self, exception_type, exception_value, traceback)

__exit__定義了代碼段結束後的一些操做,能夠這裏執行一些清除操做,或者作一些代碼段結束後須要當即執行的命令,好比文件的關閉,socket斷開等。若是代碼段成功結束,那麼exception_type, exception_value, traceback 三個參數傳進來時都將爲None。若是代碼段拋出異常,那麼傳進來的三個參數將分別爲: 異常的類型,異常的值,異常的追蹤棧。
若是__exit__返回True, 那麼with聲明下的代碼段的一切異常將會被屏蔽。
若是__exit__返回None, 那麼若是有異常,異常將正常拋出,這時候with的做用將不會顯現出來。

舉例說明:

這該示例中,IndexError始終會被隱藏,而TypeError始終會拋出。

class DemoManager(object):

    def __enter__(self):
        pass

    def __exit__(self, ex_type, ex_value, ex_tb):
        if ex_type is IndexError:
            print ex_value.__class__
            return True
        if ex_type is TypeError:
            print ex_value.__class__
            return  # return None

with DemoManager() as nothing:
    data = [1, 2, 3]
    data[4]  # raise IndexError, 該異常被__exit__處理了

with DemoManager() as nothing:
    data = [1, 2, 3]
    data['a']  # raise TypeError, 該異常沒有被__exit__處理

'''
輸出:
<type 'exceptions.IndexError'>
<type 'exceptions.TypeError'>
Traceback (most recent call last):
  ...
'''

對象的序列化

Python對象的序列化操做是pickling進行的。pickling很是的重要,以致於Python對此有單獨的模塊pickle,還有一些相關的魔術方法。使用pickling, 你能夠將數據存儲在文件中,以後又從文件中進行恢復。

下面舉例來描述pickle的操做。從該例子中也能夠看出,若是經過pickle.load 初始化一個對象, 並不會調用__init__方法。

# -*- coding: utf-8 -*-
from datetime import datetime
import pickle

class Distance(object):

    def __init__(self, meter):
        print 'distance __init__'
        self.meter = meter

data = {
    'foo': [1, 2, 3],
    'bar': ('Hello', 'world!'),
    'baz': True,
    'dt': datetime(2016, 10, 01),
    'distance': Distance(1.78),
}
print 'before dump:', data
with open('data.pkl', 'wb') as jar:
    pickle.dump(data, jar)  # 將數據存儲在文件中

del data
print 'data is deleted!'

with open('data.pkl', 'rb') as jar:
    data = pickle.load(jar)  # 從文件中恢復數據
print 'after load:', data

值得一提,從其餘文件進行pickle.load操做時,須要注意有惡意代碼的可能性。另外,Python的各個版本之間,pickle文件多是互不兼容的。

pickling並非Python的內建類型,它支持全部實現pickle協議(可理解爲接口)的類。pickle協議有如下幾個可選方法來自定義Python對象的行爲。

__getinitargs__(self)

若是你但願unpickle時,__init__方法可以調用,那麼就須要定義__getinitargs__, 該方法須要返回一系列參數的元組,這些參數就是傳給__init__的參數。

該方法只對old-style class有效。所謂old-style class,指的是不繼承自任何對象的類,每每定義時這樣表示: class A:, 而非class A(object):

__getnewargs__(self)

__getinitargs__很相似,只不過返回的參數元組將傳值給__new__

__getstate__(self)

在調用pickle.dump時,默認是對象的__dict__屬性被存儲,若是你要修改這種行爲,能夠在__getstate__方法中返回一個state。state將在調用pickle.load時傳值給__setstate__

__setstate__(self, state)

通常來講,定義了__getstate__,就須要相應地定義__setstate__來對__getstate__返回的state進行處理。

__reduce__(self)

若是pickle的數據包含了自定義的擴展類(好比使用C語言實現的Python擴展類)時,就須要經過實現__reduce__方法來控制行爲了。因爲使用過於生僻,這裏就不展開繼續講解了。

使人容易混淆的是,咱們知道, reduce()是Python的一個內建函數, 須要指出__reduce__並不是定義了reduce()的行爲,兩者沒有關係。

__reduce_ex__(self)

__reduce_ex__ 是爲了兼容性而存在的, 若是定義了__reduce_ex__, 它將代替__reduce__ 執行。

下面的代碼示例頗有意思,咱們定義了一個類Slate(中文是板岩的意思)。這個類可以記錄歷史上每次寫入給它的值,但每次pickle.dump時當前值就會被清空,僅保留了歷史。

# -*- coding: utf-8 -*-
import pickle
import time

class Slate:
    '''Class to store a string and a changelog, and forget its value when pickled.'''
    def __init__(self, value):
        self.value = value
        self.last_change = time.time()
        self.history = []

    def change(self, new_value):
        # 修改value, 將上次的valeu記錄在history
        self.history.append((self.last_change, self.value))
        self.value = new_value
        self.last_change = time.time()

    def print_changes(self):
        print 'Changelog for Slate object:'
        for k, v in self.history:
            print '%s    %s' % (k, v)

    def __getstate__(self):
        # 故意不返回self.value和self.last_change,
        # 以便每次unpickle時清空當前的狀態,僅僅保留history
        return self.history

    def __setstate__(self, state):
        self.history = state
        self.value, self.last_change = None, None

slate = Slate(0)
time.sleep(0.5)
slate.change(100)
time.sleep(0.5)
slate.change(200)
slate.change(300)
slate.print_changes()  # 與下面的輸出歷史對比
with open('slate.pkl', 'wb') as jar:
    pickle.dump(slate, jar)
del slate  # delete it
with open('slate.pkl', 'rb') as jar:
    slate = pickle.load(jar)
print 'current value:', slate.value  # None
print slate.print_changes()  # 輸出歷史記錄與上面一致

運算符相關的魔術方法

運算符相關的魔術方法實在太多了,也很好理解,不打算多講。在其餘語言裏,也有重載運算符的操做,因此咱們對這些魔術方法已經很瞭解了。

比較運算符

__cmp__(self, other)

若是該方法返回負數,說明self < other; 返回正數,說明self > other; 返回0說明self == other
強烈不推薦來定義__cmp__, 取而代之, 最好分別定義__lt__等方法從而實現比較功能。
__cmp__在Python3中被廢棄了。

__eq__(self, other)

定義了比較操做符==的行爲.

__ne__(self, other)

定義了比較操做符!=的行爲.

__lt__(self, other)

定義了比較操做符<的行爲.

__gt__(self, other)

定義了比較操做符>的行爲.

__le__(self, other)

定義了比較操做符<=的行爲.

__ge__(self, other)

定義了比較操做符>=的行爲.

下面咱們定義一種類型Word, 它會使用單詞的長度來進行大小的比較, 而不是採用str的比較方式。
可是爲了不 Word('bar') == Word('foo') 這種違背直覺的狀況出現,並無定義__eq__, 所以Word會使用它的父類(str)中的__eq__來進行比較。

下面的例子中也能夠看出: 在編程語言中, 若是a >=b and a <= b, 並不能推導出a == b這樣的結論。

# -*- coding: utf-8 -*-
class Word(str):
    '''存儲單詞的類,定義比較單詞的幾種方法'''
    def __new__(cls, word):
        # 注意咱們必需要用到__new__方法,由於str是不可變類型
        # 因此咱們必須在建立的時候將它初始化
        if ' ' in word:
            print "Value contains spaces. Truncating to first space."
            word = word[:word.index(' ')]  # 單詞是第一個空格以前的全部字符
        return str.__new__(cls, word)

    def __gt__(self, other):
        return len(self) > len(other)
    def __lt__(self, other):
        return len(self) < len(other)
    def __ge__(self, other):
        return len(self) >= len(other)
    def __le__(self, other):
        return len(self) <= len(other)

print 'foo < fool:', Word('foo') < Word('fool')  # True
print 'foolish > fool:', Word('foolish') > Word('fool')  # True
print 'bar >= foo:', Word('bar') >= Word('foo')  # True
print 'bar <= foo:', Word('bar') <= Word('foo')  # True
print 'bar == foo:', Word('bar') == Word('foo')  # False, 用了str內置的比較方法來進行比較
print 'bar != foo:', Word('bar') != Word('foo')  # True

一元運算符和函數

__pos__(self)

實現了'+'號一元運算符(好比+some_object)

__neg__(self)

實現了'-'號一元運算符(好比-some_object)

__invert__(self)

實現了~號(波浪號)一元運算符(好比~some_object)

__abs__(self)

實現了abs()內建函數.

__round__(self, n)

實現了round()內建函數. 參數n表示四舍五進的精度.

__floor__(self)

實現了math.floor(), 向下取整.

__ceil__(self)

實現了math.ceil(), 向上取整.

__trunc__(self)

實現了math.trunc(), 向0取整.

算術運算符

__add__(self, other)

實現了加號運算.

__sub__(self, other)

實現了減號運算.

__mul__(self, other)

實現了乘法運算.

__floordiv__(self, other)

實現了//運算符.

__div__(self, other)

實現了/運算符. 該方法在Python3中廢棄. 緣由是Python3中,division默認就是true division.

__truediv__(self, other)

實現了true division. 只有你聲明瞭from __future__ import division該方法纔會生效.

__mod__(self, other)

實現了%運算符, 取餘運算.

__divmod__(self, other)

實現了divmod()內建函數.

__pow__(self, other)

實現了**操做. N次方操做.

__lshift__(self, other)

實現了位操做<<.

__rshift__(self, other)

實現了位操做>>.

__and__(self, other)

實現了位操做&.

__or__(self, other)

實現了位操做|

__xor__(self, other)

實現了位操做^

反算術運算符

這裏只須要解釋一下概念便可。
假設針對some_object這個對象:

some_object + other

上面的代碼很是正常地實現了some_object的__add__方法。那麼若是遇到相反的狀況呢?

other + some_object

這時候,若是other沒有定義__add__方法,可是some_object定義了__radd__, 那麼上面的代碼照樣能夠運行。
這裏的__radd__(self, other)就是__add__(self, other)的反算術運算符。

因此,類比的,咱們就知道了更多的反算術運算符, 就不一一展開了:

  • __rsub__(self, other)
  • __rmul__(self, other)
  • __rmul__(self, other)
  • __rfloordiv__(self, other)
  • __rdiv__(self, other)
  • __rtruediv__(self, other)
  • __rmod__(self, other)
  • __rdivmod__(self, other)
  • __rpow__(self, other)
  • __rlshift__(self, other)
  • __rrshift__(self, other)
  • __rand__(self, other)
  • __ror__(self, other)
  • __rxor__(self, other)

增量賦值

這也是隻要理解了概念就容易掌握的運算。舉個例子:

x = 5
x += 1  # 這裏的+=就是增量賦值,將x+1賦值給了x

所以對於a += b, __iadd__ 將返回a + b, 並賦值給a。
因此很容易理解下面的魔術方法了:

  • __iadd__(self, other)
  • __isub__(self, other)
  • __imul__(self, other)
  • __ifloordiv__(self, other)
  • __idiv__(self, other)
  • __itruediv__(self, other)
  • __imod__(self, other)
  • __ipow__(self, other)
  • __ilshift__(self, other)
  • __irshift__(self, other)
  • __iand__(self, other)
  • __ior__(self, other)
  • __ixor__(self, other)

類型轉化

__int__(self)

實現了類型轉化爲int的行爲.

__long__(self)

實現了類型轉化爲long的行爲.

__float__(self)

實現了類型轉化爲float的行爲.

__complex__(self)

實現了類型轉化爲complex(複數, 也即1+2j這樣的虛數)的行爲.

__oct__(self)

實現了類型轉化爲八進制數的行爲.

__hex__(self)

實現了類型轉化爲十六進制數的行爲.

__index__(self)

在切片運算中將對象轉化爲int, 所以該方法的返回值必須是int。用一個例子來解釋這個用法。

class Thing(object):
    def __index__(self):
        return 1

thing = Thing()
list_ = ['a', 'b', 'c']
print list_[thing]  # 'b'
print list_[thing:thing]  # []

上面例子中, list_[thing]的表現跟list_[1]一致,正是由於Thing實現了__index__方法。

可能有的人會想,list_[thing]爲何不是至關於list_[int(thing)]呢? 經過實現Thing的__int__方法可否達到這個目的呢?

顯然不能。若是真的是這樣的話,那麼list_[1.1:2.2]這樣的寫法也應該是經過的。
而實際上,該寫法會拋出TypeError: slice indices must be integers or None or have an __index__ method

下面咱們再作個例子,若是對一個dict對象執行dict_[thing]會怎麼樣呢?

dict_ = {1: 'apple', 2: 'banana', 3: 'cat'}
print dict_[thing]  # raise KeyError

這個時候就不是調用__index__了。雖然listdict都實現了__getitem__方法, 可是它們的實現方式是不同的。
若是但願上面例子可以正常執行, 須要實現Thing的__hash____eq__方法.

class Thing(object):
    def __hash__(self):
        return 1
    def __eq__(self, other):
        return hash(self) == hash(other)

dict_ = {1: 'apple', 2: 'banana', 3: 'cat'}
print dict_[thing]  # apple

__coerce__(self, other)

實現了混合模式運算。

要了解這個方法,須要先了解coerce()內建函數: 官方文檔上的解釋是, coerce(x, y)返回一組數字類型的參數, 它們被轉化爲同一種類型,以便它們可使用相同的算術運算符進行操做。若是過程當中轉化失敗,拋出TypeError。

好比對於coerce(10, 10.1), 由於10和10.1在進行算術運算時,會先將10轉爲10.0再來運算。所以coerce(10, 10.1)返回值是(10.0, 10.1).

__coerce__在Python3中廢棄了。

其餘魔術方法

還沒講到的魔術方法還有不少,但有些我以爲很簡單,或者不多見,就再也不累贅展開說明了。

__str__(self)

對實例使用str()時調用。

__repr__(self)

對實例使用repr()時調用。str()repr()都是返回一個表明該實例的字符串,
主要區別在於: str()的返回值要方便人來看,而repr()的返回值要方便計算機看。

__unicode__(self)

對實例使用unicode()時調用。unicode()str()的區別在於: 前者返回值是unicode, 後者返回值是str。unicode和str都是basestring的子類。

當你對一個類只定義了__str__但沒定義__unicode__時,__unicode__會根據__str__的返回值自動實現,即return unicode(self.__str__());
但返回來則不成立。

class StrDemo2:
    def __str__(self):
        return 'StrDemo2'

class StrDemo3:
    def __unicode__(self):
        return u'StrDemo3'

demo2 = StrDemo2()
print str(demo2)  # StrDemo2
print unicode(demo2)  # StrDemo2

demo3 = StrDemo3()
print str(demo3)  # <__main__.StrDemo3 instance>
print unicode(demo3)  # StrDemo3

__format__(self, formatstr)

"Hello, {0:abc}".format(a)等價於format(a, "abc"), 等價於a.__format__("abc")

這在須要格式化展現對象的時候很是有用,好比格式化時間對象。

__hash__(self)

對實例使用hash()時調用, 返回值是數值類型。

__nonzero__(self)

對實例使用bool()時調用, 返回True或者False。
你可能會問, 爲何不是命名爲__bool__? 我也不知道。
我只知道該方法在Python3中更名爲__bool__了。

__dir__(self)

對實例使用dir()時調用。一般實現該方法是不必的。

__sizeof__(self)

對實例使用sys.getsizeof()時調用。返回對象的大小,單位是bytes。

__instancecheck__(self, instance)

對實例調用isinstance(instance, class)時調用。 返回值是布爾值。它會判斷instance是不是該類的實例。

__subclasscheck__(self, subclass)

對實例使用issubclass(subclass, class)時調用。返回值是布爾值。它會判斷subclass否是該類的子類。

__copy__(self)

對實例使用copy.copy()時調用。返回"淺複製"的對象。

__deepcopy__(self, memodict={})

對實例使用copy.deepcopy()時調用。返回"深複製"的對象。

__call__(self, [args...])

該方法容許類的實例跟函數同樣表現:

class XClass:
    def __call__(self, a, b):
        return a + b

def add(a, b):
    return a + b

x = XClass()
print 'x(1, 2)', x(1, 2)
print 'callable(x)', callable(x)  # True
print 'add(1, 2)', add(1, 2)
print 'callable(add)', callable(add)  # True

Python3中的差別

  • Python3中,str與unicode的區別被廢除了,於是__unicode__沒有了,取而代之地出現了__bytes__.
  • Python3中,division默認就是true division, 於是__div__廢棄.
  • __coerce__因存在冗餘而廢棄.
  • __cmp__因存在冗餘而廢棄.
  • __nonzero__更名爲__bool__.
相關文章
相關標籤/搜索