完整的腳本:https://gist.github.com/4476526全球Python中的「連接」般的變量
有問題的特定代碼是
# Cloud Files username & API key
username = ''
key = ''
# Source and destination container names
originContainerName = ''
targetContainerName = ''
...
def cloudConnect():
global originContainer
global targetContainer
global connection
print "Creating connection"
connection = cloudfiles.get_connection(username,key,servicenet=True)
print "-- [DONE]"
print "Accessing containers"
originContainer = connection.create_container(originContainerName)
targetContainer = connection.create_container(targetContainerName)
print "-- [DONE]"
return
腳本工作完全正常,但我已經在多個地方全局變量讀應該猶豫地使用,並且幾乎總是有一個更好的方法去做沒有它們的同樣的事情。這是真的?如果是這樣,我該如何解決這個腳本?對我來說,使用全局連接和容器變量而不是將這些對象作爲參數傳遞給多個函數看起來要容易得多。
我認爲一個類可能是矯枉過正的,除非有其他功能可以與它一起烘焙,一個具有一個功能的類可能只是一個功能。 –
@Lattyware:相反,如果你看腳本,還有很多其他函數使用這些全局變量,比如'uploadImg'或'containerDif'。 –
我以前見過類似於get_connection()方法的類的設計。這將創建一個,如果它不存在並將其另存爲私人成員。如果以前的連接超時,未來的連接將返回現有的連接或者甚至是新的連接。 – jdi