Frage

How do I modify class method without touching source code?

There's a class from a library which I don't want to change the source code of.

class SomeLibraryClass(object):
  def foo(self, a_var):
     print self, a_var, "hello world"

Now, I want to define my own foo method, and substitute for the original SomeLibraryClass.foo .

def foo(obj, a_var):
   print obj, a_var, "good bye"

SomeLibraryClass.foo = foo //

What should I do with the self variable?
How can I do this?

War es hilfreich?

Lösung

The same thing as you would do with self if you were in a method. self will be passed as the first parameter to your function and will be a reference to the current object. So if you want to define a function that will be used as a replacement for a method, just add self as the first parameter.

class SomeLibraryClass(object):
  def __init__(self, x):
      self.x = x

  def foo(self, y):
     print('Hello', self.x, y)

def my_foo(self, y):
    print ('Good buy', self.x, y)

SomeLibraryClass.foo = my_foo

And how to use it:

>>> s = SomeLibraryClass(33)
>>> s.foo(5)
Good buy 33 5
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top