3

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

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

4

2 回答 2

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以上)的函数都将作为类的方法包含在内。

于 2013-01-07T17:26:31.490 回答
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

然后简单地传递那个元组。

于 2013-01-07T17:26:23.050 回答