property question
Markus Jais
info at mjais.de
Thu May 23 18:51:11 EDT 2002
Chris Liechti wrote:
> Markus Jais <info at mjais.de> wrote in
> news:acjnug$q6c68$1 at ID-75083.news.dfncis.de:
>
>> hello
>>
>> Just started playing with python 2.2 and the new features.
>> Now I have a question on properties:
>>
>> class Address(object):
>>
>> def __init__(self):
>> self.firstname = ""
>> self.lastname = ""
>> self.email = ""
>>
>> def set_email(self, email):
>> print "in set email"
>> self.email = email
>>
>> def get_email(self):
>> print "in get mail"
>> return "<" + self.email + ">"
>>
>> email = property(get_email, set_email, None, 'Setting the
>> email adress')
>>
>> if __name__ == '__main__':
>> print "testing"
>>
>> a = Address()
>> a.firstname = "gandalf"
>> a.email = "wizard at middle-earth.com"
>> print a.firstname
>> print a.email
>>
>>
>> I get an endless recustion because I refer to self.email in the get_
>> and set_ method
>>
>> how can I set the value of self.email and how can I return a modified
>> version in the get method??
>
> i think the usual way is to store the value in a variable with preceeding
> underlines ("self._email" or two underlines if you want a private
> attribute)
thanks for your tip: using an underline works
but when I use two underlines with slots like this
class Address(object):
__slots__ = ('firstname', 'lastname', __email')
def __init__(self):
self.firstname = ""
self.lastname = ""
self.__email = "
def set_email(self, email):
print "in set email"
self.__email = email
......
I get this error:
Traceback (most recent call last):
File "./Address.py", line 49, in ?
a = Address()
File "./Address.py", line 24, in __init__
self.__email = ""
AttributeError: 'Address' object has no attribute '_Address__email'
but with one underline, it works just fine.
markus
More information about the Python-list
mailing list