我想写一个封装了逻辑类:连接类,静态或实例?
- 构建基于另一个类的属性和主机/端口的信息从一个配置文件
- 特定的URL进行连接
解析响应
class Foo(object): def __init__(self, a, b): self.a = a self.b = b self.connect_id = None self.response = None def something_that_requires_bar(self): # call bar pass # ...other methods
如果连接类是一堆staticmethods/classmeth的返回我正在查找的数据的ods?
class Bar(object):
def build_url(self, Foo):
# get host/port from config
# build url based on Foo's properties
return url
def connect(self, url):
# connects to the url that was built
return Bar.parse_response(the_response)
def parse_response(self, response):
# parses response
或
我也应该构建认为我需要的,这样我可以在连接后,从中提取数据的数据的对象?
class Bar(object):
def __init__(self, foo):
self.url =
def _build_url(self):
# build url based on Foo's properties
self.url = # do something with Foo
def _parse_response(self, response):
# parses response
def connect(self, url):
# connects to the url that was built
self.raw_response = urllib.urlopen(self.url).read()
self.parsed_response = self._parse_response(self.raw_response)
甚至混合?
class Bar(object):
def __init__(self, foo):
self.foo = foo
self.url = self._build_url()
def _build_url(self):
# build url based on Foo's properties
self.url = # do something with Foo
def _parse_response(self, response):
# parses response
@classmethod
def connect(cls, Foo):
# connects to the url that was built
bar = Bar(Foo)
self._build_url()
self.raw_response = urllib.urlopen(self.url).read()
self.parsed_response = self._parse_response(self.raw_response)
return bar
我会对类之间的循环依赖关系的设计保持警惕。也就是说,你有一个带'something_that_requires_bar'方法的类'Foo'和一个带'Foo'作为参数的类'Bar'。这意味着一个相当紧密的耦合(这不是一件好事)。 – Wilduck
这是我的问题之一,这就是为什么我问......这只是我看起来不正确。 – sasker