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 self-explanatory. It just checks whether the argument passed in int
or not.
def wrapper(func):
def inner():
if issubclass(x,int): pass
else: return 'invalid values'
return inner()
@wrapper
def add(x,y):
return x+y
print add('a',2)
It's throwing error saying global name 'x' is not defined
. I understand that it is not defined under inner
, but didnt know how to rectify this code? Where I'm going wrong?
A decorator is a design pattern in Python that allows a user to add new functionality to an existing object without modifying its structure. Decorators are usually called before the definition of a function you want to decorate.
You'll use a decorator when you need to change the behavior of a function without modifying the function itself. A few good examples are when you want to add logging, test performance, perform caching, verify permissions, and so on. You can also use one when you need to run the same code on multiple functions.
In fact, there are two types of decorators in Python — class decorators and function decorators — but I will focus on function decorators here.
Example:2 - @staticmethod decorator- The @staticmethod is used to define a static method in the class. It is called by using the class name as well as instance of the class.
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).You can find a good explanation of decorators here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With