首页 > 解决方案 > 在另一个类方法中调用类方法

问题描述

在 Python 3 中,如何在另一个类方法中调用继承的方法?

class A:
    name = 'foo'

    def get_name(self):
        return self.name


class B(A):

    @classmethod
    def do_other(cls):
        cls.get_name()

在 cls.get_name() 中,它抱怨“参数“self”未填充”。我怎样才能克服这个问题而不必将 do_other 更改为常规方法?

标签: pythonclassoopmethods

解决方案


您实际上只需要返回cls.get_name(cls)

class A:
    name = 'foo'
    def get_name(self):
        return self.name


class B(A):
    @classmethod
    def do_other(cls):
        return cls.get_name(cls)


print(B.do_other())

推荐阅读