2013-01-07 15 views
3

完整的腳本: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 

腳本工作完全正常,但我已經在多個地方全局變量讀應該猶豫地使用,並且幾乎總是有一個更好的方法去做沒有它們的同樣的事情。這是真的?如果是這樣,我該如何解決這個腳本?對我來說,使用全局連接和容器變量而不是將這些對象作爲參數傳遞給多個函數看起來要容易得多。

回答

5

您應該創建一個類(稱爲類似CloudContainer),包括所有那些全局變量作爲成員,並把它改寫爲(只是作爲一個開始):

class CloudContainers(object): 
    def __init__(self, username, key, originContainerName, targetContainerName): 
     self.username = username 
     self.key = key  
     self.originContainerName = originContainerName 
     self.targetContainerName = targetContainerName 

    def cloudConnect(self): 
     print "Creating connection" 
     self.connection = cloudfiles.get_connection(self.username,self.key,servicenet=True) 
     print "-- [DONE]" 
     print "Accessing containers" 
     self.originContainer = connection.create_container(self.originContainerName) 
     self.targetContainer = connection.create_container(self.targetContainerName) 
     print "-- [DONE]" 
     return 

    def uploadImg(self, new_name): 
     new_obj = self.targetContainer.create_object(new_name) 
     new_obj.content_type = 'image/jpeg' 
     new_obj.load_from_filename("up/"+new_name) 

    def getImg(name): 
     obj = self.originContainer.get_object(name) 
     obj.save_to_filename("down/"+name) 

因此,使用這些任何功能全局變量(如上面的getImguploadImg)將作爲該類的一個方法包含在內。

+0

我認爲一個類可能是矯枉過正的,除非有其他功能可以與它一起烘焙,一個具有一個功能的類可能只是一個功能。 –

+0

@Lattyware:相反,如果你看腳本,還有很多其他函數使用這些全局變量,比如'uploadImg'或'containerDif'。 –

+1

我以前見過類似於get_connection()方法的類的設計。這將創建一個,如果它不存在並將其另存爲私人成員。如果以前的連接超時,未來的連接將返回現有的連接或者甚至是新的連接。 – jdi

1

更容易,是的,但這意味着很難分辨何時以及爲什麼這些變量會發生變化。我認爲最好的答案就是你在問題中給出的答案 - 將它們作爲對象傳遞給對方。例如:

def cloud_connect(origin_container_name, target_container_name): 
    print "Creating connection" 
    connection = cloudfiles.get_connection(username, key, servicenet=True) 
    print "-- [DONE]" 
    print "Accessing containers" 
    origin_container = connection.create_container(origin_container_name) 
    target_container = connection.create_container(target_container_name) 
    print "-- [DONE]" 
    return connection, origin_container, target_container 

然後只需傳遞該元組即可。

+1

傳遞一個元組看起來像是「自己動手做的OO」,當它們可以成爲對象的成員時。 –

+0

@DavidRobinson如果你真的想要的話,我不會看到這裏的一個類的優點超過了一個元組,字典,或者可能命名爲tuple。這不是Java,並非所有東西都需要成爲一個對象。 –

+1

一個好處是封裝了實現細節,不是嗎?當然,你可以查看一個C FILE結構體,但是不是更好。傳遞元組意味着其他函數需要知道該元組的細節。 – msw