问题描述
实验
global x
x = False
class func1:
def __init__(self):
pass
def hello(self):
# global x
print x
新的
import experiment
object = experiment.func1()
z = "x"
experiment.z = True # Expection is experiment.z should work as experiment.x
experiment.hello()
输出: #o / p应该为true,因为我正尝试达到tx = True
>>>
False
>>>
问题是:有没有办法做到这一点,或者这个概念是错误的?
1楼
首先,您的代码中存在很多错误,并且存在一些不一致之处。
您刚刚将new属性添加到func1
实例。
z = "x"
t.z = True
这可能是您在寻找什么:
经验值
x = False
class Test(object):
def __init__(self, x):
self.x = x
def hello(self):
print self.x
t = Test(x)
t.hello()
newp.py
from exp import Test, t
t.x = True
t.hello()
>>> False
>>> True
2楼
使用setattr(对象,名称,值)