Ok, as always... You always learn something new with me!!
See the decorators as a function that transforms other functions. For example, @staticmethod, or...
If you want a property with "get" only, you can do this:
@property
def Prop(self):
----"""This is an example of a "get" of a property""" #Documentation of the function, and in this case, the documentation of the property too.
----return <value>
Now, you have in your class a property named "Prop" with "get" onlt, It mean you can't change the value of "Prop".
Now... how can I do a decorator?
Very easy!! Is easier that you imagine. A decorator is a function too. But is a function that receives another function.
For example, do you remember that you can do something like this…?
Prop = property(Prop)
Ok, sedate, we will do our first decorator:
def Vector(func):
----def Res(values):
--------for i in values:yield func(i)
----return Res
@Vector
def IncTwo(value):return value + 2
-->>This is equivalent to:
IncTwo = Vector(IncTwo)
Now, if you haven’t put “@Vector” above the declaration of “IncTwo”...:
If you do:
IncTwo(3) #It return 5
IncTwo(28) #It return 30
But… as “@Vector” is above the declaration of “IncTwo”… now “IncTwo” receive an iterable, and returns an iterable, applying the old “IncTwo” in each value of the iterable . For example:
for i in IncTwo((1, 5, 6, 3, 8, 2)):
----print i
#It print:
3
7
8
5
10
4
I have not talked with you about decorators in a beginning because it is a powerful tool that only Python have, and it can be shocking for you in a beginning because you haven’t seen ever something like this. I have more surprises for you very interesting one of them are decorators with parameters.