我是python的新手,并试图弄清楚如何模块化我的函数。我的项目是Restful的单元测试框架。为了简洁起见,我简化了代码。
type_parser.py
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--type', help='a or b')
args = parser.parse_args()
def A(func):
def return_func():
if args.type == "b":
return func()
else:
pass
return return_func
def B(func):
def return_func():
if args.type == "a":
return func()
else:
pass
return return_funcapi_funcs.py
from type_parser import *
class ApiFunctions:
@A
def login():
print "cool"
@B
def logout()
print "not cool"main.py
from api_funcs import *
api = ApiFunctions()
def __main__():
api.login()
api.logout()
__main__()CLI
python main.py --type=a结果
预期:
cool实际:
TypeError: return_func() takes no arguments如果我将api函数从类中直接调用并直接调用它,它就能工作,但是我想让它变得更抽象,因为有3组api。
更新-我想出了答案
class ApiFunctions:
@A
def login(self):
print "cool"
@B
def logout(self)
print "not cool"
def A(func):
def return_func(self):
if args.type == "b":
return func(self)
else:
pass
return return_func发布于 2017-01-25 17:39:49
在python中,对象本身必须解释为方法独立的一部分。因此,您需要编写:def login(self):
编写self.login有点像()*编写login(self)。由于login()不使用任何参数,所以会出现错误。
(*)说得有点像,别写
api_funcs.py
from type_parser import *
class ApiFunctions:
@A
def login(self):
print "cool"
@B
def logout(self)
print "not cool"https://stackoverflow.com/questions/41858008
复制相似问题