0

在 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 更改为常规方法?

4

2 回答 2

1

您实际上只需要返回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())
于 2020-11-14T11:10:16.833 回答
1

您可以通过创建一个临时实例来完成此操作。这是一种方式。

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


class B(A):

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


print(B.do_other())

这是第二种方式

class B(A):

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

在这里,您还可以将 A() 替换为 B(),因为 B 类继承自 A 类

于 2020-11-14T10:56:28.797 回答