2013-08-25 57 views
2

例如爲什麼我可以重寫'__setattr__'但不將其分配給__init__方法?

def __setattr__(self, name, value): 
    ... 

工作正常,但:

def __init__(self): 
    self.__setattr__ = foo 

似乎並沒有實現在任何FOO永遠不會調用。

在此先感謝。

+0

開始點:http://stackoverflow.com/questions/9057669/how-can-i-intercept-calls-to-pythons-magic-methods-in-new-s tyle-classes –

+0

'__setattr__'在類中查找,而不是在實例上查找。 – mata

回答

1

__setattr__使用類方法,而不是實例方法。檢查下面的代碼的輸出:

代碼:

def func(*args): 
    print "--Func--" 
    print args 

class A(): 
    def __setattr__(*args): 
     print "--SetAttr--" 
     print args 


a = A() 

print "a.x = 10" 
a.x = 10 
print 

A.__setattr__ = func 

print "a.y = 20" 
a.y = 20 
print 

輸出:

a.x = 10 
--SetAttr-- 
(<__main__.A instance at 0x2cb120>, 'x', 10) 

a.y = 20 
--Func-- 
(<__main__.A instance at 0x2cb120>, 'y', 20) 

你可以寫你的代碼,這樣的類方法調用一個實例方法:

class C(): 
    def __init__(self, setattr): 
     #Must access in this way since we overwrote __setattr__ already 
     self.__dict__['setattr_func'] = setattr 

    def __setattr__(self, name, value): 
     self.setattr_func(name, value) 
相關問題