Using properties

Terry Reedy tjreedy at udel.edu
Wed May 25 11:07:10 EDT 2005


<tkpmep at hotmail.com> wrote in message 
news:1117029966.799908.183830 at f14g2000cwb.googlegroups.com...
>I have a class with a name attribute, which I want to modify using
> property.The following code works just fine:
>
> class Portfolio(object):
>
>    def __init__( self, name="Port1"):
>        self.name=name
>
>    def getname(self):
>        return self._name
>
>    def setname(self,newname="Port2"):
>        self._name=newname
>
>    name=property(getname,setname,None,None)
>
> However, it no longer works if I modify getname and setname to

What does 'no longer works' mean?  Do you get and exception and traceback? 
If so, what?

>    def getname(self):
>        return self.name

>    def setname(self,newname="Port2"):
>        self.name=newname

These both look like infinite loops.  Did you got the related exceptions?
>
> Why is it so critical to have getname and setname modify _name and not
> name? The constructor does not make name a private attribute, so why do
> getname and setname have to treat it as such?

I believe because getting and setting name calls getname and setname.  The 
initializer (not constructor) setting of name results in a call to setname.

Terry J. Reedy






More information about the Python-list mailing list