python在工厂中的应用_python中的工厂方法

本文介绍了一种通过检测特定文件来确定项目类型的机制,并提供了一个改进方案,即通过工厂函数和类方法实现更简洁的设计。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

简而言之,它旨在更容易地管理许多不同的项目.

其中一个有用的方法是自动检测我正在处理的项目类型,以正确设置一些命令.

目前我正在使用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

来源: https://codeday.me/bug/20190530/1185567.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值