Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting a property doesn't work - dumb syntax error?

I'm probably making some elementary mistake...

When I initialize and look at a property of an object, fine. But if I try to set it, the object doesn't update itself. I'm trying to define a property which I can set and get. To make it interesting, this rectangle stores twice its width instead of the width, so the getter and setter have something to do besides just copying.

class Rect:
    """simple rectangle (size only) which remembers double its w,h
       as demo of properties
    """

    def __init__(self, name, w):
        self.name=name
        self.dwidth=2*w

    def dump(self):
    print "dwidth = %f"  %  (self.dwidth,)


    def _width(self):
        return self.dwidth/2.0

    def _setwidth(self,w):
        print "setting w=", w
        self.dwidth=2*w
        print "now have .dwidth=", self.dwidth

    width =property(fget=_width, fset=_setwidth)

The .dwidth member variable would normally be private, but I want to peek at it easily in an interactive session. In a Python command line, I try it out:

bash 0=> python
Python 2.7.3 (default, Aug  1 2012, 05:14:39) 
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from rectzzz import *
>>> a = Rect("ack", 10.0)
>>> a.dump()
dwidth = 20.000000
>>> a.width
10.0
>>> a.width=100
>>> a.width
100
>>> a.dump()
dwidth = 20.000000
>>> a.dwidth
20.0
>>> 

Why does .width seem to update, but the object's actual state as told by dump() and .dwidth not change? I'm especially puzzled why I never see "setting w=" followed by a number.

like image 638
DarenW Avatar asked Mar 06 '26 15:03

DarenW


1 Answers

class Rect:
    """simple rectangle (size only) which remembers double its w,h
       as demo of properties
    """

Should be:

class Rect(object):
    """simple rectangle (size only) which remembers double its w,h
       as demo of properties
    """

In python 2.x, property only works properly if you inherit from object, so that you get the new style class. By default you get old-style classes for backwards compatibility. This has been fixed in python 3.x.

like image 188
Winston Ewert Avatar answered Mar 09 '26 04:03

Winston Ewert