0

在以下代码中,Graph() 充当 Vertex 和 Edge 的代理——客户端仅通过 Graph() 访问 Vertex 和 Edge:

from rest import Resource
from elements import Vertex, Edge

class Graph(object):
    def __init__(self,db_url):
        self.resource = Resource(db_url)
        self.vertices = Vertex
        self.edges = Edge

g1 = Graph('http://localhost/one')   
g2 = Graph('http://localhost/two')

Vertex 和 Edge 访问资源对象的最佳方式是什么,而不必将其作为参数传递给 Vertex 和 Edge?

我不想将它作为参数传递的原因之一是因为 Vertex 和 Edge 具有类方法,例如 create(),它们也需要访问资源对象。

Flask/Werkzeug 使用“context locals”(http://werkzeug.pocoo.org/docs/local/)——这是正确的方法,还是有更好的方法?

4

1 回答 1

1

如果您的资源对象是唯一的,您可以将其设为单例吗?您想从类方法中使用它的事实使我认为可能是这种情况。如果它的唯一目的是提供数据库连接,你可以考虑使用连接池吗?

如果您仍然需要将它传递给您的类,您可以简单地将它分配给类属性。

class Vertex(object):
    @classmethod
    def foo(cls):
        print cls.resource

Vertex.resource = 'something'
v = Vertex()
v.foo()

这也可以在__init__

class Vertex(object):

    def __init__(self, resource):
        if not hasattr(self.__class__, 'resource'):
            self.__class__.resource = resource

    @classmethod
    def foo(cls):
        print cls.resource

resource = 'some resource'
v = Vertex(resource)
v.foo()

但实际上我的直觉是你应该考虑使用单例,在许多情况下,它可以在 Python 中简单地作为一个模块来实现。

最后,如果我可以对您的代码发表一些评论,我会发现您将类分配给复数变量名是令人困惑的。当我看到时,self.edges我会期待一个集合或一个可迭代的,而不是一个类。我也想知道为什么你会想要一个名为create. 它有什么__init__做不到的?

于 2011-06-28T04:48:05.950 回答