2011-01-21 29 views
9

考慮下面的代碼輸入一個模塊中的變量:修改使用從...進口*

#main.py 
From toolsmodule import * 
database = "foo" 

#toolsmodule 
database = "mydatabase" 

,因爲它似乎,這產生了不同的內容每個模塊中的一個變量。我如何修改main中的toolsmodule變量?以下不工作:

toolsmodule.database = "foo" 

回答

13

聽起來像是另一個很好的理由不使用from toolsmodule import *衆人的。

如果你只是做import toolsmodule,那麼你可以做toolsmodule.database = 'foo',而且一切都很美妙。

+2

我知道這一點,但我使用這些變量很多,我有很長的模塊名稱,我想避免額外的輸入。 – David

+12

因此,縮短模塊名稱:'將longmodulename導入爲sname'。現在'sname'將引用'longmodulename'。 – user225312

+4

如果您不想每次輸入'toolsmodule',可以執行以下操作:'import toolsmodule as tm'。這樣你可以保持你的名字空間健全,並保存輸入。 – miku

1

你爲什麼不那樣做:

import toolsmodule 
toolsmodule.database = "foo" 
from toolsmodule import * #bad idea, but let's say you have to.. 
print database #outputs foo 
+0

當我嘗試這個時,我相信我最終不能從toolsmodule裏面修改變量。這需要驗證。 – David

7

蟒蛇變量名只是標籤上的變量。當你import *所有這些標籤都是本地的,然後當你設置數據庫時,你只需要替換局部變量,而不是toolsmodule中的變量。因此,這樣做:

toolsmodule.py:

database = "original" 

def printdatabase(): 
    print "Database is", database 

然後運行:

import toolsmodule 
toolsmodule.database = "newdatabase" 
toolsmodule.printdatabase() 

輸出是

Database is newdatabase 

請注意,如果你再從另一個模塊還做了一個import *的變化沒有體現出來。

總之:永遠不要使用from x import *。我不知道爲什麼所有新手都堅持這樣做,儘管我知道所有文檔都說這是個壞主意。