【发布时间】:2015-10-01 10:53:02
【问题描述】:
我是一名初中级自学 Python 开发人员,
在我完成的大多数项目中,我可以看到以下过程重复。我没有任何外部家庭代码经验,我认为下面的代码不是那么专业,因为它不可重用,并且看起来它不是在一个容器中组合在一起,而是在不同模块上松散耦合的功能。
def get_query():
# returns the query string
pass
def make_request(query):
# makes and returns the request with query
pass
def make_api_call(request):
# calls the api and returns response
pass
def process_response(response):
# process the response and returns the details
pass
def populate_database(details):
# populates the database with the details and returns the status of population
pass
def log_status(status):
# logs the status so that developer knows whats happening
pass
query = get_query()
request = make_request(query)
response = make_api_call(request)
details = process_response(response)
status = populate_database(details)
log_status(status)
如何将此过程设计为基于类的设计?
【问题讨论】:
-
“它不可重复使用” - 你为什么这么认为?一些简短的、单一用途的函数肯定比试图将所有东西组合成一个更可重用。 “不同模块上的松散耦合函数” - 它们看起来在同一个模块中,松散耦合通常被认为是一件好事!
-
@jonrsharpe 对于分布在某些模块中的功能,我总是发现很难跟踪模块,复制代码并使其在第二个项目的模块结构上的另一个项目上工作
-
相关的、可重用的功能可能应该被打包到一个单独的模块中,但除此之外,你还不清楚为什么你认为你现在拥有的东西有问题。如果您将其直接转移到课程中,您最终会得到"two methods, one of which is
__init__"。 -
@jonrsharpe 我想这些课程很容易维护和调用,谢谢你的视频。
-
@jonrsharpe 我觉得你有点迂腐。有很多代码示例,其中方法(例如他/她的问题中的方法)将被包装在一个类中。这个平面文件完全可以按原样使用(我更喜欢这种方式),但是如果它也被写在一个类中,代码也是可以接受的。
标签: python oop class-design