如何在 class 方法中制作全局 class var

How to make global class var in the class method

如果满足条件,我想做一个 global instance class 'test'

我只是凭直觉写了代码,这是行不通的。我该如何解决?

class test:
    def __init__(self, a=0, b=0):
        self.a = a
        self.b = b

    def set_glob(self, check):
        if check:
            temp = test(1,1)
            global r1 = temp  ##<- syntax error at " = "
            global r2 = self  ##<- syntax error at " = "

    a=test(1,2)
    a.set_glob(True)

尝试以下操作:

global r1
r1 = temp
global r2
r2 = self

IIRC,当您声明 global x 时,您是在声明对于您所在范围的其余部分,您计划使用 x 作为全局变量。

两件事。您需要在单独的行上声明全局变量。然后,您需要担心 test 作为变量名何时出现......它在 class 定义完成之后。

class test:
    def __init__(self, a=0, b=0):
        self.a = a
        self.b = b

    def set_glob(self, check):
        if check:
            temp = test(1,1)
            global r1
            global r2
            r1 = temp
            r2 = self

a=test(1,2)
a.set_glob(True)
class test:
def __init__(self, a=0, b=0):
    self.a = a
    self.b = b

def set_glob(self, check):
    if check:
        temp = test(1,1)
        global r1 
        r1 = temp 
        global r2 
        r2 = self  

a=test(1,2)
a.set_glob(True)

解释:

首先,您需要指定您正在通过 global r1global r2 访问全局变量 r1r2,然后 assign/update 通过r1 = tempr2 = self