2013-01-16 47 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'的地方。謝謝。 –