Python - Decorators

后端 未结 5 454
礼貌的吻别
礼貌的吻别 2020-12-10 12:32

I\'m trying to learn Decorators . I understood the concept of it and now trying to implement it.

Here is the code that I\'ve written The code is se

5条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-10 12:53

    Your decorator should look like this:

    def wrapper(func):
        def inner(x, y): # inner function needs parameters
            if issubclass(type(x), int): # maybe you looked for isinstance?
                return func(x, y) # call the wrapped function
            else: 
                return 'invalid values'
        return inner # return the inner function (don't call it)
    

    Some points to note:

    • issubclass expects a class as first argument (you could replace it with a simple try/except TypeError).
    • the wrapper should return a function, not the result of a called function
    • you should actually call the wrapped function in the inner function
    • your inner function didn't have parameters

    You can find a good explanation of decorators here.

提交回复
热议问题