如果条件满足,我想创建 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)
请您参考如下方法:
两件事。您需要在单独的行上声明全局变量。然后,您需要担心作为变量名的 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
global r2
r1 = temp
r2 = self
a=test(1,2)
a.set_glob(True)
