English 中文(简体)
各种产出均以灰色表示
原标题:vars() in Python giving different output

When I run this code:

a =  1 
vars()[ a ] =  2 
print a

我获得以下产出:

2

但是,当我管理这一法典时:

def bar():
    a =  1 
    vars()[ a ] =  2 
    print a

bar()

我获得以下产出:

1

现在,我的问题是,为什么会发生这种情况,我如何使第二起案件给我同样的解决办法。

Edit:

真的找不到解决办法,但我找到了一个小的黑板。 虽然我不使用外阴:

def bar():
    a = "a"
    b = "b"
    exec a+"="+b
    print a

bar()

取得了以下成果:

b

如果任何人都能找到更好的解决办法,那将是巨大的。 我不以这种方式确定任何全球变量,也不作任何cra,以致对此不感到担忧。

问题回答

它认为,新风格类别优先于违约的<代码> >第__/code> 行为,从而打破了<代码>vars (的这种使用。 这并不是说它会影响旧风格的班级,但可能与此相关。

http://docs.python.org/library/Functions.html#vars:


vars([object]) Return the __dict__ attribute for a module, class, instance, or any other object with a __dict__ attribute.

模块和实例等物体具有可更新的 dict__/code> 属性;但其他物体可能对其_dict__ /code> 属性有书面限制(例如,新式的类别使用dict氧来预防直接的字典更新)。

不用说,var像当地人。 值得注意的是,当地字典仅有用,因为对当地字典的更新被忽视。


您是否可以评论一下为什么<代码>本身= valsetattr(自己,x , val)赢得你的班级工作?

<代码>vars(>的转让未作界定。 因此,在不同的情景和/或假冒版本和(或)实施方面,它可能会产生不同的结果。 虽然用这种方式改变当地变量可能令人惊讶(我曾经尝试利用这种变数来控制集团结果),但这非常不可行,可能会中断任何时间。





相关问题
Simple JAVA: Password Verifier problem

I have a simple problem that says: A password for xyz corporation is supposed to be 6 characters long and made up of a combination of letters and digits. Write a program fragment to read in a string ...

Case insensitive comparison of strings in shell script

The == operator is used to compare two strings in shell script. However, I want to compare two strings ignoring case, how can it be done? Is there any standard command for this?

Trying to split by two delimiters and it doesn t work - C

I wrote below code to readin line by line from stdin ex. city=Boston;city=New York;city=Chicago and then split each line by ; delimiter and print each record. Then in yet another loop I try to ...

String initialization with pair of iterators

I m trying to initialize string with iterators and something like this works: ifstream fin("tmp.txt"); istream_iterator<char> in_i(fin), eos; //here eos is 1 over the end string s(in_i, ...

break a string in parts

I have a string "pc1|pc2|pc3|" I want to get each word on different line like: pc1 pc2 pc3 I need to do this in C#... any suggestions??

Quick padding of a string in Delphi

I was trying to speed up a certain routine in an application, and my profiler, AQTime, identified one method in particular as a bottleneck. The method has been with us for years, and is part of a "...

热门标签