oop - Overwriting a field's method in Python -
i have custom class instantiate twice in second class:
[edit: old code wasn't capturing issue is, i'm rewriting make clearer. foo going process network events (and need multiple connections, hence why bar have multiple foo fields , can't inherit) using callback function. in bar class, want overwrite callback different. rewriting callb in foo won't work, because inherit in other instances]
class foo(object): def __init__(self, x): self._x = x #when event happens, call callb() self.on_certain_event(callback=callb) def callb(self): print self._x def run(self): waitforeventsinfinitely() # class bar(object): def __init__(self): self._foo = foo(5) #overwrite existing callback method in foo class! self._foo.callb = self.callb def callb(self): print self._x * 10 def run(self): waitforeventsinfinitely() # not going write t f = foo(2) f.run() b = bar() b.run()
[when run() called in foo, works correctly. however, cannot overwrite callb method of foo bar - self._x should referred foo trying call bar]
however, when running code, receive error "bar has no attribute '_x'" rather expected value of 50. obviously, self in bar's test still referring bar, not foo calling method. have expected internal foo self._foo field in bar.
i suspect problem has name mangling, haven't been able find descriptive source when have fields on self having methods overwritten. examples seem when i'm inheriting different class.
ok short lesson on how classes in python work: function stored on class object (a "method") automatically fetched descriptor (which describes how getl attributes objects) binds methods class or instance used it.
for example:
foo.test
is unbound method of class foo: object created descriptor on foo
knows fetched class object
foo().test
is bound method of instance of class foo: method stores instance of foo
used fetch function. instance automatically passed first argument when call resulting object , that's why write self
first parameter when define method.
so, trying this:
- get raw function
test
classbar
(not through descriptor) - bind function instance of
foo
- store function on foo instance
so, how it:
import types class bar(object): def __init__(self): self._foo = foo(5) raw_function = bar.test_bar.__func__ # 1) bound_to_foo = types.methodtype(raw_function, self._foo) # 2) self._foo.test = bound_to_foo # 3) def test(self): print self._x * 10
see this question more details on descriptors.
Comments
Post a Comment