gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 01:46:27 24 4
gpt4 key购买 nike

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

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

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

最佳答案

它不起作用,因为 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')

关于python - 无法在另一个静态方法中调用静态方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70842483/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com