properties and formatting with self.__dict__
Michele Simionato
mis6 at pitt.edu
Wed Feb 19 15:05:41 EST 2003
"Mark McEahern" <mark at mceahern.com> wrote in message news:<mailman.1045664347.7149.python-list at python.org>...
> I hope the following example is not too obtuse, but it shows something that
> I thought was surprising about properties. Attempting to format a string
> (traceback follows, with code at the end of the message) with named
> parameters and expecting the property to show up naively via self.__dict__
> generates this error:
>
> Traceback (most recent call last):
> File "./junk.py", line 23, in ?
> print p
> File "./junk.py", line 19, in __repr__
> return template % self.__dict__
> KeyError: full_name
>
> I'm not asking for workarounds because there are many and they are obvious.
> I guess I'm wondering whether this is a likely stumbling block in the
> intersection of string formatting and the use of properties?
>
> Thanks,
>
> // mark
>
> #!/usr/bin/env python
>
> class Person(object):
>
> def __init__(self, first_name, last_name):
> self.first_name = first_name
> self.last_name = last_name
>
> def get_full_name(self):
> return '%s %s' % (self.first_name, self.last_name)
>
> full_name = property(get_full_name)
>
> def __repr__(self):
> template = '<Person ' \
> 'first=%(first_name)s ' \
> 'last=%(last_name)s ' \
> 'full=%(full_name)s'
> return template % self.__dict__
>
> p = Person('mark', 'mceahern')
>
> print p
>
> -
The problem is that writing "full_name = property(get_full_name)" in
the class scope, as you do, put "full_name" in the class dictionary,
not in the instance dictionary (this is the standard behaviour).
You should write in the __init__ method something like
"self.full_name=property(self.get_full_name)"
This will give you as output
<Person first=mark last=mceahern full=<property object at 0x8108a7c>
and from there you should be able yourself to figure out where to go ;)
Michele
More information about the Python-list
mailing list