Declarative properties
Artur Siekielski
artur.siekielski at gmail.com
Thu Oct 11 11:39:29 EDT 2007
On Oct 11, 4:21 pm, "sjdevn... at yahoo.com" <sjdevn... at yahoo.com> wrote:
> In practice, it turns out to be a lot less work to deal with that
> occasionally than to always deal with lugging around internal
> attributes and external properties when they're really not needed. By
> writing everything as properties up front you're just creating more
> work for yourself, and it's generally considered bad practice in
> Python to have default getters/setters (whether part of a property or
> not).
Ok, I appreciate your and Marc's argument. So I see that a pythonic
way is
using public attributes, and it works in real life. Automatic
"generation" of
getters/setters is a nice thing when using Java style of properties,
ie. no
public fields.
> > 2. Properties define (a part of) public interface of a class. When
> > using fields for public
> > access, you must tell this explicitly in documentation, or use name
> > convention.
>
> Property vs. attribute doesn't make any difference here: both of them
> are public, and part of the external interface, unless they're named
> with a leading underscore.
Nice thing about properites is that they are defined in more
declarative way -
in class body. Attributes are "defined" in a piece of code (which can
be long
and can contain loops etc.) by assigning a value to 'self'.
> > 3. Using properties as first-class objects gives possibilities to use
> > declarative approaches
> > for constructing them.
>
> This doesn't make any sense. Properties and attributes are both
> objects in python.
Attribute is an object which has value specific for the time it's get
from object.
It is separated from containing object - relation to it is lost.
Python property is an object that describes how to get/set a specific
attribute of
containing object - any time. It describes relationship between the
two.
By declarative method I mean something like a function that takes a
property object
and returns modified property object:
def not_none(prop):
def new_fset(self, obj):
if obj is not None:
prop.fset(self, obj)
else:
raise 'Cannot set None value'
return property(prop.fget, new_fset, prop.fdel)
And then:
class Person(object):
...
name = not_none( property(_get_name, _set_name) )
More information about the Python-list
mailing list