首页 > 解决方案 > 在 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?

标签: pythonoopself

解决方案


您不能使用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')。如果它不是实例方法,则最好将其定义为类定义之外的函数。


推荐阅读