2012-03-22 70 views

回答

13

當屬性不​​存在於實例/類/父類中時,會調用__getattr__魔術方法。你會用它來提高一個特殊的例外丟失屬性:

class Foo(object): 
    def __getattr__(self, attr): 
     #only called what self.attr doesn't exist 
     raise MyCustonException(attr) 

如果你想定製訪問類的屬性,您需要在元類/類型定義__getattr__

class BooType(type): 
    def __getattr__(self, attr): 
     print attr 
     return attr 

class Boo(object): 
    __metaclass__ = BooType 

boo = Boo() 
Boo.asd # prints asd 
boo.asd # raises an AttributeError like normal 

如果要自定義所有屬性訪問,請使用__getattribute__魔術方法。

+0

是不是修改實例不是類屬性訪問? – 2012-03-22 10:26:26

+0

@ RomanA.Taycher我已經擴展了我的答案。 – agf 2012-03-22 10:32:57

2

agf's answer是正確的,實際上我要給出的答案是基於它的,並且有一定的功勞。

只給更詳細的類屬性的一面,這是實際上是在這裏的問題(而不是__getattr____getattribute__之間的差異)的一部分,我想添加一個參考an answer I wrote to a different similar question,肚裏更詳細地介紹類和實例屬性之間的區別,實現方式以及爲什麼需要使用元類來影響類屬性查找。

+2

嘿,你對另一個問題的回答很好,但這不是真正的答案。你應該在這裏添加一些內容或張貼這個問題或我的答案評論。 – agf 2013-04-24 15:04:44