Newbie: Why doesn't this work

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Tue Jan 1 16:54:27 EST 2008


On Tue, 01 Jan 2008 13:01:24 -0800, petr.jakes.tpc wrote:

>> > My question is: is it possible to set the "property" for any
>> > attribute when I do not know what will be the name of the attribute
>> > in the future?
>>
>> Uhm... I don't understand the question. Perhaps if you think of a
>> concrete case...?
> 
> Thanks for reply,
> 
> few minutes after i posted my question, I have realized my posting is
> probably a "nonsense".
> 
> If I understand it properly, it is necessary, in the respect of
> encapsulation, to define attributes inside the class (even it is
> possible to add a new attribute to the existing object outside class
> definition).
> 
> The meaning of my question was:
> Is it possible to define some general sort of set/get/del/doc rules for
> the attributes which are defined in the code AFTER the instantiation of
> an object.
> 
> I am sending this question even I feel such a "on the fly" creation of
> the attribute is probably not a good trick.

Like all dynamic modification of classes, it is liable to abuse, but 
Python allows such things and trusts the programmer not to be foolish.

class Parrot(object):
    pass


def set_property(cls, propertyname, defaultvalue=None, docstring=''):
    """Make a readable, writable but not deletable property."""
    privatename = '_' + propertyname
    setattr(cls, privatename, defaultvalue)
    def getter(self):
        return getattr(self, privatename)
    def setter(self, value):
        setattr(self, privatename, value)
    setattr(cls, propertyname, property(getter, setter, None, docstring))


set_property(Parrot, 'colour', 'red', 
    """Parrots have beautiful coloured plumage.""")



Now that you know how to do it, please don't. Except for the lack of 
docstring, the above is much better written as:


class Parrot(object):
    colour = 'red'





-- 
Steven



More information about the Python-list mailing list