Tutorial by Examples

The @property decorator can be used to define methods in a class which act like attributes. One example where this can be useful is when exposing information which may require an initial (expensive) lookup and simple retrieval thereafter. Given some module foobar.py: class Foo(object): def __...
If you want to use @property to implement custom behavior for setting and getting, use this pattern: class Cash(object): def __init__(self, value): self.value = value @property def formatted(self): return '${:.2f}'.format(self.value) @formatted.setter def ...
When you inherit from a class with a property, you can provide a new implementation for one or more of the property getter, setter or deleter functions, by referencing the property object on the parent class: class BaseClass(object): @property def foo(self): return some_calculate...
While using decorator syntax (with the @) is convenient, it also a bit concealing. You can use properties directly, without decorators. The following Python 3.x example shows this: class A: p = 1234 def getX (self): return self._x def setX (self, value): self._x =...

Page 1 of 1