简体   繁体   中英

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()

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM