python 无法在另一个静态方法内调用静态方法

qxsslcnc  于 2022-11-28  发布在  Python
关注(0)|答案(2)|浏览(259)

我有一个包含静态方法的类,我想在该类中使用另一个静态方法来调用该方法,但它返回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

解决此问题的最佳方法是什么?
我想把代码保持在这种格式,其中有一个类包含这些静态方法,并使它们能够相互调用。

xqkwcwgp

xqkwcwgp1#

它不起作用,因为method1abc类的属性,而不是在全局范围内定义的东西。
必须通过直接引用类来访问它:

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

或者使用一个classmethod而不是staticmethod,这样会给予方法访问它的类对象。我推荐使用这种方式。

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

vfh0ocws2#

@staticmethod不能调用其他静态方法,而**@classmethod可以调用它们。简而言之,@classmethod@staticmethod**功能更强大。

我在我对@classmethod vs @staticmethod in Python的回答中解释了更多关于**@静态方法@类方法的信息,还在我对What is an "instance method" in Python?的回答中解释了关于示例方法**的信息:

相关问题