在Python中使用代理模式时,代理类如何访问调用对象中的状态?
在下面的代码中,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 具有类方法,例如 create(),也需要访问资源对象。
Flask/Werkzeug 使用“上下文局部变量”(http://werkzeug.pocoo.org/docs/local/< /a>) -- 这是正确的方法吗,还是有更好的方法?
In the following code, Graph() is acting as a proxy to Vertex and Edge -- clients only access Vertex and Edge through Graph():
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')
What are the best ways for Vertex and Edge to access the resource object, without having to pass it as a param to Vertex and Edge?
One of the reasons I don't want to pass it as a param is because Vertex and Edge have classmethods, such as create(), that need access to the resource object too.
Flask/Werkzeug uses "context locals" (http://werkzeug.pocoo.org/docs/local/) -- is that the right approach here, or is there a better way?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您的资源对象是唯一的,您可以将其设为单例吗?您想从类方法中使用它这一事实让我认为情况可能就是这样。如果它的唯一目的是提供数据库连接,您可以考虑使用连接池吗?
如果您仍然需要将其传递给您的类,您可以简单地将其分配给类属性。
这也可以在 __init__ 中完成:
但实际上我的直觉是您应该考虑使用单例,在许多情况下,它可以在 Python 中简单地作为模块实现。
最后,如果我可以对您的代码做一些评论,我发现您将类分配给复数变量名是令人困惑的。当我看到 self.edges 时,我期望的是一个集合或一个可迭代对象,而不是一个类。我还想知道为什么您需要一个名为
create
的类方法。它能做什么__init__
不能做什么?If your resource object is unique, could you make it a singleton? The fact that you want to use it from a class method makes me think that it's probably the case. If its only purpose is to provide the database connection, could you consider using a connection pool?
If you still need to pass it to your classes, you can simply assign it to class attributes.
This can also be done in
__init__
:But really my intuition is that you should look into using a singleton, which in many cases can be implemented in Python simply as a module.
Finally if I can make a couple of remarks about your code, I find it confusing that you're assigning classes to plural variable names. When I see
self.edges
I would expect a collection or an iterable, not a class. I also wonder why you would want a class method calledcreate
. What does it do that__init__
cannot do?