当前位置: 代码迷 >> python >> 使用变量更改对象的全局变量值以访问对象的全局变量
  详细解决方案

使用变量更改对象的全局变量值以访问对象的全局变量

热度:95   发布时间:2023-06-16 10:24:01.0

实验

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
>>>

问题是:有没有办法做到这一点,或者这个概念是错误的?

首先,您的代码中存在很多错误,并且存在一些不一致之处。

您刚刚将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

使用setattr(对象,名称,值)