如何解决在python类中,应如何从同一类的另一个方法调用该类的非实例方法?
考虑此类包含不带自变量的方法的类:
class C:
def foo(a,b):
# function does something
# It is not an instance method (i.e. no 'self' argument)
def bar(self):
# function has to call foo() of the same class
foo('hello','world')
在bar()中调用非实例方法foo()时,以上代码错误。某种程度上,即使它是同一类主体中的一个方法,也无法识别名称“ foo”。 如果它是一个实例方法,则可以使用self.foo()进行调用,但实际情况并非如此。
以上示例中调用foo()的最佳方法是什么?
# 1 Like this?
C.foo('hello','world')
# 2 Like this?
self.__class__.foo('hello','world')
# Something else?
解决方法
您不能使用 def 关键字定义函数,也不能紧随其后插入任何缩进块。
class C:
def foo(a,b):
# function does something
# It is not an instance method (i.e. no 'self' argument)
return 0
def bar(self):
# function has to call foo() of the same class
foo('hello','world')
,然后调用C.foo('hello','world')。如果不是实例方法,则最好将其定义为类定义之外的函数。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。