Python中的全局"连接"变量

Nor*_*lik 3 python cloudfiles python-2.7

完整脚本: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
Run Code Online (Sandbox Code Playgroud)

该脚本工作得非常好,但是我已经在多个地方读过全局变量应该犹豫不决的使用,并且几乎总有一种更好的方法可以在没有它们的情况下做同样的事情.这是真的?如果是这样,我应该如何修复此脚本?对我来说,使用全局连接和容器变量似乎更容易,而不是将这些对象作为参数传递给多个函数.

Dav*_*son 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)
Run Code Online (Sandbox Code Playgroud)

因此,使用这些全局变量(如任何功能getImguploadImg以上)将被包括作为类的方法.