Python 继承:修改对象的父 class

Python inheritance: modify a parent class of an object

我 need/want 修改父 class 并且在正确导入时遇到问题。子对象仍然使用 "old" 版本的 class.

文件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()。我该如何正确执行此操作?

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

您的问题可能通过在本模块中编写继承的 class B 得到更好的解决,但如果您真的想修改父 class,您可以:

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!

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

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!