从类方法函数调用变量到普通方法

mik*_*nim -1 python class

我想从一个类方法调用一个变量到同一类内的另一个方法:

class A():
    @classmethod
    def b(cls):
        cls.g = 5
    def c(self):
        if self.g < 1:
            print("TestA")
        else:
            print("TestB")
Run Code Online (Sandbox Code Playgroud)

进行时:

x = A()
x.c()
Run Code Online (Sandbox Code Playgroud)

我得到:

AttributeError: 'A' object has no attribute 'g'
Run Code Online (Sandbox Code Playgroud)

我已经阅读并搜索了类似的案例,但没有找到。大多数处理从init方法调用变量,但这不适用于此方法。

Blo*_*let 6

如果您不.b()事先运行,那么您.g根本不存在,...根本不存在。

__init__在您的类中添加一个函数,然后在其中声明.g以确保至少存在。