[Tutor] decorators, __call__ (able) objects

wesley chun wescpy at gmail.com
Wed Jul 15 21:02:05 CEST 2009


>>> > Can some one give, or point to some good examples of how @decorators
>>> > work, and __call__ (able) objects?
>
> simple example of calling a class
>
> class myKlass(object):
>
>     def __call__(self, *args, **kws):
>          print "i was called"
>
> >>> test = myKlass()
> >>> test()
> i was called


close. the example was right, but the description wasn't accurate...
you meant, "calling an instance." i'm going to plagarize and rip this
right out of section 14.1.4 from "Core Python Programming:"

"Python provides the __call__() special method for classes, which allows a
programmer to create objects (instances) that are callable. By default, the
__call__() method is not implemented, meaning that most instances are
not callable. However, if this method is overridden in a class deļ¬nition,
instances of such a class are made callable. Calling such instance objects is
equivalent to invoking the __call__() method. Naturally, any arguments
given in the instance call are passed as arguments to __call__()."

as far as decorators go, kent's tutorial is great place to start. here
are 2 more articles plus PEP 318, where they were defined:

http://www.ibm.com/developerworks/linux/library/l-cpdecor.html
http://www.artima.com/weblogs/viewpost.jsp?thread=240808
http://www.python.org/dev/peps/pep-0318

in addition, i devoted section 11.3.6 of Core Python to decorators.

finally, it should be mentioned that starting in 2.6, you can now
decorate *classes*, as seen here in PEP 3129:

http://www.python.org/dev/peps/pep-3129/

hope this helps!
-- wesley
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
"Core Python Programming", Prentice Hall, (c)2007,2001
"Python Fundamentals", Prentice Hall, (c)2009
    http://corepython.com

wesley.j.chun :: wescpy-at-gmail.com
python training and technical consulting
cyberweb.consulting : silicon valley, ca
http://cyberwebconsulting.com


More information about the Tutor mailing list