【问题标题】:Call class method in another class method在另一个类方法中调用类方法
【发布时间】:2020-11-14 10:42:04
【问题描述】:
在 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 更改为常规方法的情况下克服这个问题?
【问题讨论】:
标签:
python
class
oop
methods
【解决方案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()
这里你也可以用 B() 替换 A(),因为 B 类继承自 A 类
【解决方案2】:
您实际上只需返回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())