Note that there are some explanatory texts on larger screens.

plurals
  1. POOverwriting a field's method in Python
    text
    copied!<p>I have a custom class which I instantiate twice in a second class:</p> <p>[EDIT: The old code wasn't really capturing what my issue is, I'm rewriting to make it clearer. Foo is going to process network events (and I need multiple connections, hence why Bar will have multiple Foo fields and can't just inherit) by using a callback function. In the Bar class, i want to overwrite the callback to do something different. Rewriting callb in Foo won't work, because I do inherit from it in other instances]</p> <pre><code>class Foo(object): def __init__(self, x): self._x = x #When an 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 THE EXISTING CALLBACK METHOD IN THE Foo CLASS! self._foo.callb = self.callb def callb(self): print self._x * 10 def run(self): waitForEventsInfinitely() # Not going to actually write t f = Foo(2) f.run() b = Bar() b.run() </code></pre> <p>[When run() is called in a Foo, it works correctly. However, I cannot overwrite the callb method of Foo from Bar - the self._x which should be referred to by Foo is trying to call from Bar]</p> <p>However, when running the code, I receive the error "Bar has no attribute '_x'" rather than my expected value of 50. Obviously, the self in Bar's test is still referring to Bar, not the Foo which is actually calling the method. I would have expected it to be the internal Foo self._foo field in Bar.</p> <p>I suspect my problem has something to do with name mangling, but I haven't been able to find a descriptive source when I have fields on self having their methods overwritten. Most examples seem to be when I'm inheriting from a different class.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload