【问题标题】:Python - Unable to call static method inside another static methodPython - 无法在另一个静态方法中调用静态方法
【发布时间】:2022-11-18 07:48:44
【问题描述】:

我有一个有静态方法的类,我想在这个类中有另一个静态方法来调用该方法,但它返回NameError: name ''method_name' is not defined

我正在尝试做的事情的例子。

class abc():
    @staticmethod
    def method1():
        print('print from method1')

    @staticmethod
    def method2():
        method1()
        print('print from method2')

abc.method1()
abc.method2()

输出:

print from method1
Traceback (most recent call last):
  File "test.py", line 12, in <module>
    abc.method2()
  File "test.py", line 8, in method2
    method1()
NameError: name 'method1' is not defined

解决此问题的最佳方法是什么?

我想将代码保留为这种格式,其中有一个类包含这些静态方法并让它们能够相互调用。

【问题讨论】:

  • 您需要的是classmethod,而不是staticmethod。或者,您可以对类名进行硬编码,并使用 abc.method1()method2 调用它。
  • 即使它们是静态的,它们也会在类后面命名空间,因此您需要类 obj。如果都是静态方法,您应该考虑使用模块。
  • 啊谢谢你。我明白为什么它现在不起作用了。

标签: python python-3.x methods call static-methods


【解决方案1】:

它不起作用,因为 method1abc 类的属性,而不是在全局范围内定义的东西。

您必须通过直接引用类来访问它:

    @staticmethod
    def method2():
        abc.method1()
        print('print from method2')

或者使用类方法而不是静态方法,这将使方法可以访问其类对象。我推荐使用这种方式。

    @classmethod
    def method2(cls): # cls refers to abc class object
        cls.method1()
        print('print from method2')

【讨论】:

    【解决方案2】:

    @staticmethod不能调用其他静态方法,@classmethod可以调用。简而言之,@类方法@静态方法.

    我解释更多关于@静态方法@类方法my answer@classmethod vs @staticmethod in Python

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多