color version - PET: Python Entre Todos - Python Argentina
color version - PET: Python Entre Todos - Python Argentina
color version - PET: Python Entre Todos - Python Argentina
You also want an ePaper? Increase the reach of your titles
YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.
A first example:<br />
Identity:<br />
def identity(C):<br />
return C<br />
Returns the same class we are decorating.<br />
>>> @identity<br />
... class A(object):<br />
... pass<br />
...<br />
>>> A()<br />
<br />
Change a class totally:<br />
return X<br />
>>> @replace_with_X<br />
... class MyClass():<br />
... pass<br />
...<br />
>>> MyClass<br />
<br />
In the previous case we see that the class was changed completely for a brand new<br />
different class.<br />
Instance:<br />
def instantiate(C):<br />
return C()<br />
def abuse(C):<br />
return "hello"<br />
>>> @abuse<br />
... class A(object):<br />
... pass<br />
...<br />
>>> A()<br />
Traceback (most recent call last):<br />
File "", line 1, in<br />
TypeError: 'str' object is not callable<br />
>>> A<br />
'hello'<br />
Similar to one of the examples you’ve read at the beginning, this example shows us that<br />
a decorator’s return has to have a similar interface as the object we are decorating, that<br />
way it makes more sense to change the use of the original object, for a changed one.<br />
Replace with a new class:<br />
def replace_with_X(C):<br />
class X():<br />
pass<br />
>>> @instantiate<br />
... class MyClass():<br />
... pass<br />
...<br />
>>> MyClass<br />
<br />
As last example of class decorators we’ve seen a decorator that once applied, instantiates<br />
the class and links this object to its name. This can be seen as a way to implement the<br />
Singleton design pattern, studied in programming. # wikipedia singleton quote<br />
To finish:<br />
Where can I find decorators<br />
Permissions in Django<br />
@login_required<br />
def my_view(request):<br />
...<br />
URL routing in Bottle