peaky76
peaky76

Reputation: 137

Python: Is it possible to override/extend an instance method of one class when it is used in another class?

I'm planning out a Python project. I'm going to have classes that use instances of other classes. Is it possible to override/extend a method from within another class, like this:

class Foo:

    a = Bar()
    b = Bar()
    c = Bar()

class Baz:

    x = Bar()
    y = Bar()
    z = Bar()

class Qux:

    p = Bar()
    q = Bar()
    r = Bar()

class Bar:

    def __init__(self):
        pass

    def do_something():
        # Thing to do

Baz.x.do_something() # Does the same thing 
Qux.p.do_something() # Does the same thing

Foo.a.do_something() # Does something slightly different

The slightly different behaviour is going to depend on the Foo class instance so I can't create a new method for it in the Bar class. NB Most of the behaviours of Bar will be the same. I just want to do an extra step in the Foo.a.do_something()

Upvotes: 0

Views: 115

Answers (1)

DeepSpace
DeepSpace

Reputation: 81594

Not in a clean way. In overall this seems like a bad idea. How will you know when do_something behaves how? It's gonna be a debugging nightmare.

If do_something needs to do something different, subclass Bar and implement it differently in each subclass.

class Bar:    
    def do_something():
        # Does something

class Bar2(Bar):    
    def do_something():
        # Does something else

Upvotes: 1

Related Questions