2013-01-16 119 views
3

我想使用函数属性将变量值设置为使用全局变量的替代方法。但是有时候我会给一个函数指定另一个短名称。行为似乎总是做我想做的事情,即将值分配给函数,无论我使用长名还是短名,如下所示。这有什么危险吗?函数属性

def flongname(): 
    pass 

f = flongname 
f.f1 = 10 
flongname.f2 = 20 
print flongname.f1, f.f2 

最后一行返回10 20显示出不同的功能名称指的是同一个函数对象。对?

回答

5

id显示fflongname都是对同一对象的引用。

>>> def flongname(): 
...  pass 
... 
>>> f = flongname 
>>> id(f) 
140419547609160 
>>> id(flongname) 
140419547609160 
>>> 

所以是的 - 您所遇到的行为是预期的。

+0

了'id'内置确实是正确的方式来表明重命名函数引用同一个对象。谢谢。 –

3
f = flongname # <- Now f has same id as flongname 
f.f1 = 10 # <- a new entry is added to flongname.__dict__ 
flongname.f2 = 20 # <- a new entry is added to flongname.__dict__ 
print flongname.f1, f.f2 # Both are refering to same dictionary of the function 

看着它,因为它是被似乎并不危险,只记得别人正在修改其dict

In [40]: f.__dict__ 
Out[40]: {} 

In [41]: flongname.__dict__ 
Out[41]: {} 

In [42]: f.f1=10 

In [43]: flongname.__dict__ 
Out[43]: {'f1': 10} 

In [44]: f.__dict__ 
Out[44]: {'f1': 10} 

In [45]: flongname.f2 = 20 

In [46]: f.__dict__ 
Out[46]: {'f1': 10, 'f2': 20} 
+0

很高兴知道这是属性去了'dict'的地方。谢谢。 –