There are really smart guys around the world, especially in python world. One of these guys (Sean Ross) suggested this to be used instead of the regular property in python:
I've started using these idiom and I'm happy to be able not to bloat my classes with getters and setters...
"""
Rather than defining your get/set/del methods at the class level, as is usually done, e.g.
class MyClass(object):
def __init__(self):
self._foo = "foo"
def getfoo(self):
return self._foo
def setfoo(self, value):
self._foo = value
def delfoo(self):
del self._foo
foo = property(getfoo, setfoo, delfoo, "property foo's doc string")
I would like to suggest the following alternative idiom:
"""
class MyClass(object):
def __init__(self):
self._foo = "foo"
self._bar = "bar"
def foo():
doc = "property foo's doc string"
def fget(self):
return self._foo
def fset(self, value):
self._foo = value
def fdel(self):
del self._foo
return locals() # credit: David Niergarth
foo = property(**foo())
def bar():
doc = "bar is readonly"
def fget(self):
return self._bar
return locals()
bar = property(**bar())
I've started using these idiom and I'm happy to be able not to bloat my classes with getters and setters...
Comments
obj = MyClass()
obj.foo.doc
or
obj.foo.__doc__
or
help(obj.foo)
or
MyClass.foo.__doc__
prints the doc...
also there is another modification to the idiom in:
http://kbyanc.blogspot.com/2007/06/python-property-attribute-tricks.html
where the doc string of the property function is passed as the doc string of the property, a nice one...