是否可以从父类调用子类的函数?

时间:2019-06-22 07:55:23

标签: python

class A(object):
    def xx():
        # do something

    def yy():
        # do something

class B(A):
    def func():
        # do something

# How to make it possible?
a = A()
a.func()

现在,我想将func()添加到类A,但是我不能更改类A,因此我创建了A的子类,并将func()添加到该子类。如何从实例调用func()?

我尝试从B类开始,但是有很多实例,因此我需要更改许多位置。有更好的方法吗?理想的是A级。

# This works, however, I need to change A() to B() everywhere.
# Are there easy ways to do it without changing A() to B()?
a = B()
a.func()

2 个答案:

答案 0 :(得分:1)

您可以使用setattr()doc):

class A:
    def xx(self):
        print('xx')

    def yy(self):
        print('yy')

class B(A):
    def func(self):
        print('func')

setattr(A, 'func', B.func) # or setattr(A, B.func.__name__, B.func)

a = A()
a.func()

打印:

func

答案 1 :(得分:-1)

您不能这样做,因为类B是从类A继承而来的,所以您可以使用B.xx()但不能使用A.func()。

有关Python继承的更多信息,请查看here

正如Andrej所说,您可以使用setattr()方法为类A定义新属性。 在here中查找有关setattr()方法的更多信息。