使用__call__函数的类装饰器

时间:2019-07-19 15:26:23

标签: python

我正在使用sqlachemy连接到MYSQL,并且在执行每个查询后需要关闭连接。

计划使用类装饰器来完成此任务。这是我的简短代码。

我收到此错误:
TypeError: __call__() missing 1 required positional argument: 'args'

class Connection(object):

    class close_sqlalchemy_connection(object):
        def __init__(self, f):
            print("inside myDecorator.__init__()")
            self.f = f

        def __call__(self, args):
            print("inside myDecorator.__call__()", *args )
            self.f(args)
            print("function decorted")

    def __init__(self):
        self.mysql_engine = 'mysql_engine' # this will be mysql sqlalchemy connection

    @close_sqlalchemy_connection
    def execute_query(self):
        print('execute_query')


i = Connection()
i.execute_query()

1 个答案:

答案 0 :(得分:0)

尝试使用装饰器功能,如果您不需要设置中的其他参数(例如

),则更加容易
@decorator(*params)
def method(...):

这里是一个示例:

from functools import wraps 
class Connection(object):

    def close_sqlalchemy_connection(f):
        @wraps (f)
        def inner(*args, **kwargs):
            # args[0] is instance itself, if you want to do things with it
            return f(*args, **kwargs)
        return inner 


    def __init__(self):
        self.mysql_engine = 'mysql_engine' # this will be mysql sqlalchemy connection

    @close_sqlalchemy_connection
    def execute_query(self):
        print('execute_query')


i = Connection()
i.execute_query()