Python 在另一个类方法中调用类方法
在Python3中,如何在另一个类方法中调用继承的方法Python 在另一个类方法中调用类方法,python,class,oop,methods,Python,Class,Oop,Methods,在Python3中,如何在另一个类方法中调用继承的方法 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更改为常规方法?您可以通
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更改为常规方法?您可以通过创建临时实例来实现这一点。 这是一种方式
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继承的您可以通过创建一个临时实例来实现这一点。 这是一种方式
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继承的您实际上只需要返回
cls.get\u name(cls)
实际上,您只需返回
cls.get\u name(cls)