Main Content
Python decorators - your own, staticmethod and classmethod Archive - Originally posted on "The Horse's Mouth" - 2010-05-14 07:18:04 - Graham Ellis
Python Decorators are wrappers that you may apply around methods. So they're rather like the bread around a sandwich.
There are a number of standard decorators provided with Python - such as @classmethod and @staticmethod (see [here] ) which allow you to turn methods into unbound (static, class) ones. You can also set up your own decorator - there's and example of that [here] .
Here's how I can define my own decorator:
def summat(f):
"Definition of your own decorator"
def action(*args,**kwargs):
result = f(*args,**kwargs)
print "Err ... ",
return result
return action
How I wrap a method using it:
@summat
def getstuff(self):
return self.stuff
And an example of how I call it:
print them.getstuff()
When should you use decorators? There are lots of potential uses - the first "classic" demonstration is for logging calls to methods, but it could also be used to provide overall / management controls on actions - such as ensuring that databases are open, or keeping tables of details of widgets in a GUI.
Illustration © - public domain image
Some other articles
Y115 - Additional Python Facilities Some gems from Intermediate Python Command line parameter handling in Python via the argparse module Json load from URL, recursive display, Python 3.4 Running an operating system command from your Python program - the new way with the subprocess module Json is the new marshall, pickle and cPickle / Python Python - an interesting application Handling JSON in Python (and a csv, marshall and pickle comparison) JSON from Python - first principles, easy example Teaching dilemma - old tricks and techniques, or recent enhancements? A demonstration of how many Python facilities work together Python regular expressions - repeating, splitting, lookahead and lookbehind Joining a MySQL table from within a Python program Factory methods and SqLite in use in a Python teaching example Running operating system commands from your Python program This article Model - View - Controller demo, Sqlite - Python 3 - Qt4 Connecting Python to sqlite and MySQL databases Regular Expressions in Python Python - what is going on around me? Python - how it saves on compile time Serialization - storing and reloading objects Testing code in Python - doctest, unittest and others Python Regular Expressions A series of tyre damages Ignore case in Regular Expression Regular expressions made easy - building from components Turning objects into something you can store - Pickling (Python) Buffering output - why it is done and issues raised in Tcl, Perl, Python and PHP Sending an email from Python Python - listing out the contents of all variables Python 3000 - the next generation Keeping your regular expressions simple Python to MySQL Splitting the difference What and why for the epoch Examples - Gadfly, NI Number, and Tcl to C interface The elegance of Python Y112 - Objects - Intermediate Nesting decorators Defining an object that is a modified standard type in Python with in Python - examples of use, and of defining your own context Object and Static methods - what is the difference; example in Python 3 Setting up and tearing down with the Python with keyword Deciding whether to use parameters, conditional statements or subclasses Spike solution, refactoring into encapsulated object methods - good design practise A good example of recursion - a real use in Python Changing what operators do on objects - a comparison across different programming languages Object factories in C++, Python, PHP and Perl Python base and inherited classes, test harness and unit testing - new examples Python Properties - how and why Really Simple Class and Inheritance example in Python Inheritance, Composition and Associated objects - when to use which - Python example Backquote, backtic, str and repr in Python - conversion object to string Metaclasses (Python) and Metatables (Lua) Static variables in functions - and better ways using objects A demonstration of how many Python facilities work together A list of special method and attribute names in Python Python - some common questions answered in code examples Defining static methods in Python Should Python classes each be in their own file? The Light bulb moment when people see how Object Orientation works in real use This article Mixins example in Python Multiple inheritance in Python - complete working example The Multiple Inheritance Conundrum, interfaces and mixins Methods that run on classes (static methods) in Python How do I set up a constant in Python? TypeError: super() argument 1 must be type, not classobj (Python) Python - fresh examples of all the fundamentals Calling base class constructors Equality, sameness and identity - Python Using a utility method to construct objects of different types - Python Python - formatting objects What are factory and singleton classes? __new__ v __init__ - python constructor alternatives? Practical polymorphism in action Pieces of Python Comparison of Object Oriented Philosophy - Python, Java, C++, Perl Think about your design even if you don't use full UML Class, static and unbound variables Overloading of operators on standard objects in Python Using a Python dictionary as a holder of object attributes