首页 / PYTHON / python中的工厂方法
python中的工厂方法
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了python中的工厂方法,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1986字,纯文字阅读大概需要3分钟。
内容图文
我正在做以下小项目:
https://github.com/AndreaCrotti/project-organizer
简而言之,它旨在更容易地管理许多不同的项目.
其中一个有用的方法是自动检测我正在处理的项目类型,以正确设置一些命令.
目前我正在使用classmethod“匹配”函数和一个迭代各种“匹配”的检测函数.
我相信可能有更好的设计,但找不到它.
有任何想法吗?
class ProjectType(object):
build_cmd = ""
@classmethod
def match(cls, _):
return True
class PythonProject(ProjectType):
build_cmd = "python setup.py develop --user"
@classmethod
def match(cls, base):
return path.isfile(path.join(base, 'setup.py'))
class AutoconfProject(ProjectType):
#TODO: there should be also a way to configure it
build_cmd = "./configure && make -j3"
@classmethod
def match(cls, base):
markers = ('configure.in', 'configure.ac', 'makefile.am')
return any(path.isfile(path.join(base, x)) for x in markers)
class MakefileOnly(ProjectType):
build_cmd = "make"
@classmethod
def match(cls, base):
# if we can count on the order the first check is not useful
return (not AutoconfProject.match(base)) and (path.isfile(path.join(base, 'Makefile')))
def detect_project_type(path):
prj_types = (PythonProject, AutoconfProject, MakefileOnly, ProjectType)
for p in prj_types:
if p.match(path):
return p()
解决方法:
这是合理使用工厂函数作为类方法.
一种可能的改进是让所有类继承自单个父类,该父类具有单个类方法,该类方法包含detect_project_type中的所有逻辑.
也许这样的事情会起作用:
class ProjectType(object):
build_cmd = ""
markers = []
@classmethod
def make_project(cls, path):
prj_types = (PythonProject, AutoconfProject, MakefileOnly, ProjectType)
for p in prj_types:
markers = p.markers
if any(path.isfile(path.join(path, x)) for x in markers):
return p()
class PythonProject(ProjectType):
build_cmd = "python setup.py develop --user"
markers = ['setup.py']
class AutoconfProject(ProjectType):
#TODO: there should be also a way to configure it
build_cmd = "./configure && make -j3"
markers = ['configure.in', 'configure.ac', 'makefile.am']
class MakefileOnly(ProjectType):
build_cmd = "make"
markers = ['Makefile']
内容总结
以上是互联网集市为您收集整理的python中的工厂方法全部内容,希望文章能够帮你解决python中的工厂方法所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。