下面是Python的2.7.12文檔(3.4.12新風格classes¶特殊方法查找。)讀出的代碼片段:爲什麼在這裏調用metaclass __getattribute__?
除了繞過任何實例中的 利益屬性正確性,隱特殊方法查找通常也繞過 的
__getattribute__()
方法,即使對象的元類:>>> class Meta(type): ... def __getattribute__(*args): ... print "Metaclass getattribute invoked" ... return type.__getattribute__(*args) ... >>> class C(object): ... __metaclass__ = Meta ... def __len__(self): ... return 10 ... def __getattribute__(*args): ... print "Class getattribute invoked" ... return object.__getattribute__(*args) ... >>> c = C() >>> c.__len__() # Explicit lookup via instance Class getattribute invoked 10 >>> type(c).__len__(c) # Explicit lookup via type Metaclass getattribute invoked 10 >>> len(c) # Implicit lookup 10
我的問題是,爲什麼metacl執行type(c).__len__(c)
時調用屁股__getattribute__
?
由於type(c)
產生C
,此聲明可以改寫爲C.__len__(c)
。 C.__len__
是在類C
中定義的未綁定方法,它可以在C.__dict__
中找到,那麼爲什麼Meta
涉及查找?