[Python] Python Decorator class with arguments

Discussão em 'Python' iniciado por Stack, Abril 4, 2025.

  1. Stack

    Stack Membro Participativo

    I have a simple Python class that I want to use to add named hooks to a program I am writing. I try to run the below code and I get the following output.


    Code:

    hooks = {}

    class hook(object):
    def __init__(self, f, hook):
    if hook not in hooks:
    hooks[hook] = []

    hooks[hook].append({"module": f.__module__, "func": f})
    self.f = f

    def __call__(self, *args):
    f(*args)

    @hook("test")
    def testHook():
    print "hi"


    Output:

    Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
    TypeError: __init__() takes exactly 3 arguments (2 given)


    How can I fix this? I am using Python 2.7

    Continue reading...

Compartilhe esta Página