Python继承:修改对象的父类

时间:2018-12-17 10:24:12

标签: python inheritance super

我需要/想要修改父类,并且在正确导入时遇到问题。子对象仍然使用该类的“旧”版本。

文件A (某些我不想直接修改的库):

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

文件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!

找不到新添加的函数f()。我该如何正确地做到这一点?

2 个答案:

答案 0 :(得分:-1)

仅因为您的类也称为A,这并不意味着它将覆盖另一个模块中先前定义的类A。即使可以,类B也不会自动依赖它。

在此模块中编写继承的类B可能会更好地解决您的问题,但是,如果您确实要修改父类,则可以:

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!

答案 1 :(得分:-1)

您最好的选择可能是猴子打补丁,例如:

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!