21.01.2015 Views

color version - PET: Python Entre Todos - Python Argentina

color version - PET: Python Entre Todos - Python Argentina

color version - PET: Python Entre Todos - Python Argentina

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Understanding Decorators in <strong>Python</strong><br />

Author: Juanjo Conti<br />

Juanjo is a Systems Engineer. He has been programming in<br />

<strong>Python</strong> for 5 years now and he uses the language to work,<br />

investigate and have fun.<br />

Blog: http://juanjoconti.com.ar<br />

Email: jjconti@gmail.com<br />

Twitter: @jjconti<br />

The beginning of everything<br />

Everything in <strong>Python</strong> is an object<br />

• Identity<br />

• Type<br />

• Value<br />

In <strong>Python</strong> everything is an object. Integers, strings, lists, tuples and other weirder things:<br />

modules are objects, the source code is an object. Everything is an object. EVERYTHING.<br />

Each object has 3 features or attributes: identity, type and value.<br />

A note about what’s next<br />

Next article is not an article properly speaking, it is the relief of a talk that was<br />

presented in oral form, not from an audio medium but from my memory! I hope the<br />

reader will find it useful.<br />

Objects<br />

Let’s see some examples. Number ‘1’ is an object. Using the built-in id we can find its<br />

identity. Its type is int and its value is obviously 1.<br />

>>> a = 1<br />

>>> id(a)<br />

145217376<br />

>>> a.__add__(2)<br />

3<br />

Because it’s an object, we can apply to it some of its methods. __add__ is the method<br />

that is called when we use the + symbol.<br />

Other objects:<br />

Introduction<br />

The topics I treated in the talk are the following ones:<br />

• The beginning of everything<br />

• What is a decorator<br />

• Decorator functions<br />

• Decorators with parameters<br />

• Decorator classes<br />

• Decorating classes<br />

[1, 2, 3] # lists<br />

5.2 # floats<br />

"hello" # strings<br />

Functions<br />

If everything is an object, so are the functions.<br />

def greeting():<br />

print "hello"<br />

We can obtain a function’s id using id, access its attributes or even make another name<br />

refer to the same function object:

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!