简体   繁体   中英

Python inheritance: modify a parent class of an object

I need/want to modify a parent class and have problems with proper import. The child object still uses the "old" version of the class.

File A (some lib which I do not want to modify directly):

class A(object):
    def __init__(self):
        self.contentA = "42"
        print("A.__init__() ausgeführt")
    def m(self):
        print("A.m() aufgerufen")
class B(A):
    def __init__(self):
        #A.__init__(self)
        super().__init__()
        self.contentB = "43"
        print("B.__init__() ausgeführt")
    def m(self):
        #A.m(self)
        super().m()
        print("B.m() aufgerufen")

File B :

import somelib as demo

class A(demo.A):
    def __init__(self):
        super().__init__()
    def f(self):
        '''
        new function for A!
        '''
        print("A.f():", self.contentA)

if __name__ == "__main__":
    b = demo.B()
    b.m()
    print("b.contentB: " + str(b.contentB))
    print("b.contentA: " + str(b.contentA))
    b.f() # not found!

The newly added function f() is not found. How do I have to do this correctly?

Just because your class is also called A this doesn't mean that it will overwrite a previously defined class A in another module. Even if it would, the class B would not depend on it automatically.

Your problem is likely better solved by writing your inherited class B in this module, but if you really want to modify the parent class you can:

import somelib as demo

def f(self):
    '''
    new function for A!
    '''
    print("A.f():", self.contentA)

demo.A.f = f  # assign f to the f attribute of A

if __name__ == "__main__":
    b = demo.B()
    b.m()
    print("b.contentB: " + str(b.contentB))
    print("b.contentA: " + str(b.contentA))
    b.f() # found!

Your best bet is probably monkey patching, eg:

import somelib as demo

def f(self):
    '''
    new function for A!
    '''
    print("A.f():", self.contentA)

demo.A.f = f


if __name__ == "__main__":
    b = demo.B()
    b.m()
    print("b.contentB: " + str(b.contentB))
    print("b.contentA: " + str(b.contentA))
    b.f() # should now be found!

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