平常我们写一些python任务脚本执行,都是增加函数再执行函数。
这样代码一多人一多就不好管理,很多函数没有公用,出现代码的冗余。
#task.py
def email(data):
pass
def message(data):
pass
def func1():
print('func1')
email('func1')
def func2():
print('func2')
message('func2')
func1()
func2()
简单优化一下,将一些函数为公用。再将任务函数的命名规则定义好,例如批量执行函数名以func开头的函数,这样任务开发者就只需要按规则增加任务函数放进Executor类里就行了。
#common.py
def email(data):
pass
def message(data):
pass
#task.py
from common import email,message
class Executor(object):
def func1(self):
print('func1')
email('func1')
def func2(self):
print('func2')
message('func2')
def main(self):
for func_name in dir(self):
if func_name.startswith('func'):
getattr(self, func_name)()
Executor().main()
当然还可以再进一步的优化,可以将任务函数的命名规则继续定义,例如需要发邮件的就以email开头,需要发信息的以message开头,然后任务执行完将参数return。
自己的任务类继承任务基类。最后实例化自己的任务类就会自动执行所有的任务函数了,是不是代码逻辑就更加清晰了呢。
#common.py
class ExecutorBase(object):
def __init__(self):
self.main()
def __email(self, data):
pass
def __message(self, data):
pass
def main(self):
print(dir(self))
for func_name in dir(self):
if func_name.startswith('email'):
result = getattr(self, func_name)()
self.__email(result)
elif func_name.startswith('message'):
result = getattr(self, func_name)()
self.__message(result)
#task.py
from common import ExecutorBase
class Executor(ExecutorBase):
def email_func(self):
print('email_func')
return 'email_func'
def message_func(self):
print('message_func')
return 'message_func'
Executor()
网友评论