Python 中的全局"connection"类变量



完整脚本:https://gist.github.com/4476526

所讨论的具体代码是

# 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

脚本工作得很好,但是我在多个地方读到全局变量应该犹豫地使用,并且几乎总是有一个更好的方法来做同样的事情没有他们。这是真的吗?如果是这样,我应该如何修复这个脚本?对我来说,使用全局连接和容器变量似乎更容易,而不是在多个函数中传递这些对象作为参数。

您应该创建一个类(称为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)都将作为类的方法包含。

更容易,是的,但这意味着很难判断这些变量何时以及为什么被更改。我认为最好的答案是你在你的问题中给出的——把它们作为一个物体传下去。例句:

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

然后简单地传递这个元组

最新更新