Metody Pythona: domyślne wartości parametrów są oceniane RAZ
Znalazłem dziwny problem z podklasowaniem i aktualizacją słownika w klasach New-Style:
Python 2.6.2 (r262:71605, Apr 14 2009, 22:40:02) [MSC v.1500 32 bit (Intel)] on
win32
>>> class a(object):
... def __init__(self, props={}):
... self.props = props
...
>>> class b(a):
... def __init__(self, val = None):
... super(b, self).__init__()
... self.props.update({'arg': val})
...
>>> class c(b):
... def __init__(self, val):
... super(c, self).__init__(val)
...
>>> b_inst = b(2)
>>> b_inst.props
{'arg': 2}
>>> c_inst = c(3)
>>> c_inst.props
{'arg': 3}
>>> b_inst.props
{'arg': 3}
>>>
W debugowaniu, w drugim wywołaniu (c(3)
) widać to wewnątrza
konstruktorself.props
jest już równy{'arg': 2}
, i kiedyb
konstruktor jest wywoływany po tym, staje się{'arg': 3}
dla obu obiektów!
również kolejność wywoływania konstruktorów to:
a, b # for b(2)
c, a, b # for c(3)
Jeśli się zmieniszself.props.update()
zself.props = {'arg': val}
wb
konstruktor, wszystko będzie dobrze i będzie działać zgodnie z oczekiwaniami
Ale naprawdę muszęaktualizacja ta własność, nie do zastąpienia