python - 在 python 类中,我应该如何从同一类的另一个方法调用该类的非实例方法?
问题描述
考虑这个包含没有 self 参数的方法的类:
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')。如果它不是实例方法,则最好将其定义为类定义之外的函数。
推荐阅读
- java - java文件中出现意外的日志json
- curl - CURL:如何编码 url 后缀
- java - W/System.err: com.parse.ParseRequest$ParseRequestException: i/o 失败
- apache-kafka - 无法从 org.apache.kafka.common 禁用 DEBUG 级别日志
- linux - linux中的route和route -n有什么区别,为什么有时我不能用“route”获得正确的IP?
- mysql - COLLATION 'utf8_general_ci' 对 CHARACTER SET 'utf8mb4' 无效
- c# - Azure CI/CD 用于同一项目中的多个解决方案
- .net - .NET AMQP 服务总线请求/响应
- go - Go Println 为 String() 中的恐慌抑制堆栈跟踪
- android - 如何以编程方式创建级别列表?