Mais conteúdo relacionado
Mais de P3 InfoTech Solutions Pvt. Ltd. (20)
Python Programming Essentials - M38 - Decorators
- 2. © SkillBrew http://skillbrew.com
What is a decorator?
A decorator is a callable that takes a
function as an argument and returns a
replacement function
Useful to wrap new capabilities inside a
function
- 4. © SkillBrew http://skillbrew.com
Creating a decorator – our objective
>>> @logger
... def foo1(x, y=1):
... return x * y
>>> foo1(5, 4)
Arguments were: (5, 4), {}
20
>>> foo1(1)
Arguments were: (1,), {}
1
- 6. © SkillBrew http://skillbrew.com
Functions are first class objects
# all objects in Python inherit from a common
baseclass
>>> issubclass(int, object)
True
>>> def foo():
... pass
>>> foo.__class__
<type 'function'>
>>> issubclass(foo.__class__, object)
True
- 7. © SkillBrew http://skillbrew.com
Functions can be passed as arguments
>>> def add(x, y):
... return x + y
>>> def sub(x, y):
... return x - y
>>> def apply(func, x, y):
... return func(x, y)
>>> apply(add, 2, 1)
3
>>> apply(sub, 2, 1)
1
- 8. © SkillBrew http://skillbrew.com
Functions can be returned from other functions
>>> def outer():
... def inner():
... print "Inside inner"
... return inner
...
>>> foo = outer()
>>> foo
<function inner at 0x...>
>>> foo()
Inside inner
- 9. © SkillBrew http://skillbrew.com
Function closures
>>> def outer():
... x = 1
... def inner():
... print x
... return inner
>>> foo = outer()
>>> foo.func_closure
(<cell at 0x...: int object at 0x...>,)
- 11. © SkillBrew http://skillbrew.com
Simple decorator
>>> def outer(some_func):
... def inner():
... print "before some_func"
... ret = some_func()
... return ret + 1
... return inner
>>> def foo():
... return 1
>>> decorated = outer(foo)
>>> decorated()
before some_func
2
- 12. © SkillBrew http://skillbrew.com
Logger decorator
>>> def logger(func):
... def inner(*args, **kwargs):
... print "Arguments were: %s, %s" % (args,
kwargs)
... return func(*args, **kwargs)
... return inner