gpt4 book ai didi

python - 连接类、静态还是实例?

转载 作者:太空宇宙 更新时间:2023-11-03 19:26:51 24 4
gpt4 key购买 nike

我正在尝试编写一个类,将逻辑封装为:

  • 根据另一个类的属性和配置文件中的主机/端口信息构建特定的 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

连接类应该是一堆返回我正在查找的数据的静态方法/类方法吗?

    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

最佳答案

理想情况下,单个类应该代表一组清晰且有凝聚力的行为。有时并不总是清楚什么是最合适的,但就您而言,我会将您的每个步骤编码为不同的类或函数,如下所示:

def build_url(foo):
# build the url from foo
return the_url

def get_response(url):
# do the connection, read the response
return the_response

def parse_response(response):
# parse the response
return parsed_response

response = get_response(build_url(foo_object))
stuff_you_want = parse_response(response)

如果这些步骤中的任何一个需要更多的内部逻辑,而这些逻辑在类构造中可以更好地服务,那么您可以使用类而不是函数来执行相同的操作。例如url 和响应解析逻辑位于类中可能是有意义的:

class Url(object):
def __init__(self, foo):
self._url = self._build_url_from_foo(foo)

def _build_url_from_foo(self, foo):
# do the url stuff
return the_url

def url_string(self):
return self._url

class ResponseWrapper(object):
def __init__(self, response):
self._response = response

def parse(self):
# parsing logic here
return parsed_response

response = ResponseWrapper(get_response(Url(foo)))
response.parse()

关于python - 连接类、静态还是实例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7811854/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com