properties and formatting with self.__dict__

Bengt Richter bokr at oz.net
Sat Feb 22 17:39:34 EST 2003


On Fri, 21 Feb 2003 19:56:40 GMT, Alex Martelli <aleax at aleax.it> wrote:

><posted & mailed>
>
>Andrew Bennetts wrote:
>   ...
>>> > You should write in the __init__ method something like
>>> > 
>>> > "self.full_name=property(self.get_full_name)"
>   ...
>>>   Except that, unfortunately, properties won't work as instance
>>>   attributes,
>>> only as class attributes.
>> 
>> I think you could fairly easily write your own instanceproperty that did
>> work with instances, though.
>
>Could you?  Maybe I'm having a blind spot, but, without having a
>custom metaclass (redefining __getattribute__ differently from the
>implementation in object), how would you do it?  I.e. how would you
>code a type instanceproperty such that:
>
>
>class UIP(object):
>
>    def getfullname(self): return 'Monty Python'
>
>    def __init__(self):
>        self.fulname = instanceproperty(self.getfullname)
>
>x = UIP()
>print x.fullname
>
>
>would result in x.getfullname() being _called_?  I just can't
>see how, and I'd like to learn -- thanks!
>
Taking advantage of your typo (?) to define a regular property 'fullname' to
call bound methods stored as instance attributes, maybe something like:
(not tested beyond what you see ;-)

====< UIP.py >===============================================
def instanceproperty(*args): return args
    
class UIP(object):

    def getfullname(self): return 'Monty Python'

    def __init__(self):
        self.fulname = instanceproperty(self.getfullname)

    def _get_fulname(self):
        return self.fulname[0]()    # call bound method stored in instance
    def _set_fulname(self, val):
        self.fulname[1](val)
    fullname = property(_get_fulname,_set_fulname)
        
        
x = UIP()
print x.fullname
=============================================================
output:

[14:46] C:\pywk\clp>UIP.py
Monty Python

Regards,
Bengt Richter




More information about the Python-list mailing list