Writing good Classes in Python
·
Kiran Gangadharan
This post is the highlight of Raymond Hettinger’s talk “Python’s Class Development Toolkit” at PyCon US 2013.
Things to keep in mind while writing Classes:
- Inherit from
object()
- Instance variables for information unique to an instance
- Class variables for data shared among all instances
- Regular methods need self to operate on instance data
- Class methods implement alternative constructors. They need
cls
so they can create subclass instances as well - Static methods attach functions to classes. They don’t need
either
self
orcls
. Static methods improve discoverability and require context to be specified. - A
property()
lets getter and setter methods be invoked automatically by attribute access. This allows Python Classes to expose their instance variables freely. - The
__slots__
variable implements Flyweight Design Pattern by supressing instance dictionaries. - Use
__perimeter
to preserve namespace when subclassing. The underlying variable name changes based on the caller.
This is an example with all the above practices implemented:
|
|