Skip to main content
 首页 » 编程设计

python之创建类

2025年02月15日15lautakyan007

我是 python 的新手,正在尝试弄清楚如何模块化我的函数。我的项目是 Restful API 的单元测试框架。为简洁起见,我简化了代码。

类型解析器.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" 

主.py

from api_funcs import * 
 
api = ApiFunctions() 
 
def __main__(): 
    api.login() 
    api.logout() 
 
__main__() 

命令行

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 

请您参考如下方法:

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