【问题标题】:In a python class, how should I invoke a non-instance method of the class from another method of the same class? [duplicate]在 python 类中,我应该如何从同一类的另一个方法调用该类的非实例方法? [复制]
【发布时间】:2020-10-14 06:49:08
【问题描述】:

考虑这个类包含没有 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?

【问题讨论】:

  • 您将foo的第一个参数命名为a而不是传统的self这一事实并没有改变任何东西,这是一个完全正常的方法。
  • 所以你应该完全正常地称呼它,如self.foo
  • 我认为您正在寻找的东西是静态方法。你可以看看python doc docs.python.org/3/library/functions.html#staticmethod
  • 我也很困惑这个方法是classmethod还是staticmethod? Classmethods 和 staticmethods 需要一个装饰器,而实例方法需要一个“self”参数,而 foo() 没有这 3 个。那么你会怎么称呼它呢?毕竟是静态方法吗?
  • 如果它是一个静态方法,你应该用@staticmethod这样装饰它。然后,您可以随意调用它:C.foo(...)、self.foo(...)。只是 foo(...) 永远不会起作用,因为它不是一个全局函数。

标签: python oop self


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2023-03-15
    • 1970-01-01
    • 1970-01-01
    • 2015-06-10
    • 1970-01-01
    • 2013-10-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多