property question

Chris Liechti cliechti at gmx.net
Thu May 23 17:58:52 EDT 2002


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)
 
> I thought with properties there are no more endless recursion
> maybe I just do not understand but I do not see an advantage right now
> over __getattr__ and __setattr__ and __dict__

the advantage is that you can convert an data attribute later to execute 
code through the getter/setter. you can do this per attribute, easier than 
to mess with __getattr__ etc. which might be used for other things and 
needs the __dict__ trick in __init__
 
> please help me to understand the new stuff. 
> is there something in the online documentation?? I couldn't find
> anythong about properties

i think there is an example in the "what's new" document of 2.2 which you 
find on python.org under the 2.2 releases&docs

chris


-- 
Chris <cliechti at gmx.net>




More information about the Python-list mailing list