创建课程?

时间:2017-01-25 17:34:29

标签: python class

我是python的新手,并试图弄清楚如何模块化我的功能。我的项目是Restful API的单元测试框架。为简洁起见,我简化了代码。

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_func

api_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

1 个答案:

答案 0 :(得分:1)

在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"