简体   繁体   English

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

[英]Is it possible to call a function of a subclass from parent class?

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

Now I want to add func() to class A, however I CANNOT change class A, so I created a subclass of A and add func() to the subclass.现在我想将 func() 添加到 A 类,但是我不能更改 A 类,所以我创建了 A 的子类并将 func() 添加到子类中。 How can I call func() from A instance?如何从 A 实例调用 func()?

I tried to initiate with class B, however, there are many instances, so I need to change many many locations.我试图用B类启动,但是,有很多实例,所以我需要更改很多很多位置。 Is there a better way to do it?有没有更好的方法来做到这一点? Ideally with class A.最好是 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()

You could use setattr() ( doc ):您可以使用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()

Prints:印刷:

func

You can't do such thing because class B inherits from Class A not the reverse, so you can use B.xx() but you can't use A.func().你不能这样做,因为 B 类继承自 A 类而不是相反,所以你可以使用 B.xx() 但你不能使用 A.func()。

For more information about inheritance in Python, look here有关 Python 中继承的更多信息,请查看此处

As Andrej said, you can use setattr() method to define new attribute for class A. Look here for more information about setattr() method.正如 Andrej 所说,您可以使用setattr()方法为类 A 定义新属性。查看此处了解有关setattr()方法的更多信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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