父类方法可以调用将在子类中实现的抽象方法吗? [英] Can a parent's class method call an abstract method which will be implemented in a child class?

查看:0
本文介绍了父类方法可以调用将在子类中实现的抽象方法吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个包含两个方法的父类:

class Parent():
    @abstractmethod
    @staticmethod
    def functionA():
       pass
    
    def functionB():
       return __class__.functionA() + 1

我实现了一个子类:

class Child(Parent):
    def functionA(): # this function is different for each kind of child
        return 3

归根结底,子类的目的只是调用functionB()。 它起作用了吗?当然,我可以将functionB()放到子类中并使其工作,但因为functionB()对于每种子类都是相同的,所以我不想为每个类编写重复的代码?

另外,我在这里使用__class__合适吗?

推荐答案

首先,functionB本身应该是类方法。

@classmethod
def functionB(cls):
    return cls.functionA() + 1

其次,您仍然必须将functionA装饰为每个子类中的静态方法;否则,您将用实例方法替换继承的静态方法。

class Child(Parent):

    @staticmethod
    def functionA():
        return 3

这篇关于父类方法可以调用将在子类中实现的抽象方法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆