我想覆蓋Python類的__setattr__
方法,因爲每次實例屬性更改其值時都要調用另一個函數。不過,我不希望在__init__
方法這種行爲,因爲這在初始化過程中我設置一些屬性,其將要在以後使用:到目前爲止,我有這個解決方案在運行時覆蓋__setattr__
,而無需在運行覆蓋__setattr__
:
class Foo(object):
def __init__(self, a, host):
object.__setattr__(self, 'a', a)
object.__setattr__(self, 'b', b)
result = self.process(a)
for key, value in result.items():
object.__setattr__(self, key, value)
def __setattr__(self, name, value):
print(self.b) # Call to a function using self.b
object.__setattr__(self, name, value)
然而,我想避免這些object.__setattr__(...)
並在__init__
方法結束時覆蓋__setattr__
:
class Foo(object):
def __init__(self, a, b):
self.a = a
self.b = b
result = self.process(a)
for key, value in result.items():
setattr(self, key, value)
# override self.__setattr__ here
def aux(self, name, value):
print(self.b)
object.__setattr__(self, name, value)
我與試圖和object.__setitem__['__setitem__'] = self.aux
,但這些嘗試都沒有效果。我已閱讀this section of the data model reference,但它看起來像自己__setattr__
的任務有點棘手。
怎麼可能在__init__
的末尾覆蓋__setattr__
,或者至少有一個pythonic解決方案,其中__setattr__
只在構造函數中以正常方式調用?
哇!哇哇!我偶然發現了這一點,幾乎將它解僱了,但事實證明,這正是我需要解決類似問題的方法。這個答案中有一些嚴重的Python魔法。對不起,我無法註冊100次:p – velis 2014-08-07 08:09:46