user1427661
user1427661

Reputation: 11774

Overriding a class's method definition

Let's say I have a class, FooClass, that has a method, foo_method, defined. This class is in a third party library, and I want to explicitly override it. I have a number of classes that inherit from FooClass, so I don't want to override foo_method for every single subclass. Instead, I'd like to override the class's method definition without digging into the third party library code. When I try the obvious way,

from thirdparty import FooClass

class FooClass(object):

  def foo_method():
    newstuff

I get strange behavior -- NotImplementedErrors and such. Am I missing something?

Upvotes: 3

Views: 219

Answers (2)

Milo Wielondek
Milo Wielondek

Reputation: 4352

The first thing that comes to mind is to use simple inheritance ala

from thirdparty import FooClass

class MyUpdatedClass(FooClass):

  def foo_method():
    newstuff

Upvotes: 4

Martijn Pieters
Martijn Pieters

Reputation: 1121544

You are redefining the class locally; that won't change the original class or affect anyone using it elsewhere.

You can monkeypatch the method on the class:

from thirdparty import FooClass

orig_foo_method = FooClass.foo_method

def new_foo_method(self):
    # do new stuff
    # perhaps even call orig_foo_method(self)

FooClass.foo_method = new_foo_method

Now any code that tries to call .foo_method() on instances of FooClass anywhere in your Python interpreter will find and call your new_foo_method() method instead.

Upvotes: 5

Related Questions