Proper usage of properties in 2.2
Sandy Norton
sandskyfly at hotmail.com
Thu Nov 22 08:35:30 EST 2001
More information about the Python-list mailing list
Thu Nov 22 08:35:30 EST 2001
- Previous message (by thread): Proper usage of properties in 2.2
- Next message (by thread): Vpython download problem
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Hi, I've been playing round with properties in 2.2b2 and I'm having a bit of trouble understanding what I _shouldn't_ be doing when I use them. For example this simple code doesn't work: Python 2.2b2 (#26, Nov 16 2001, 11:44:11) [MSC 32 bit (Intel)] on win32 Type "copyright", "credits" or "license" for more information. IDLE 0.8 -- press F1 for help >>> Example #1 >>> class Room: def __init__(self, width, length, fixed='length'): self.width = width self.length = length self.fixed = fixed def get_area(self): area = self.width * self.length return area def set_area(self, area): if self.fixed == 'length': self.width = area / self.length if self.fixed == 'width': self.length = area / self.width area = property(get_area, set_area, None, "Area of Room instance") >>> r = Room(10.0, 30.0, fixed='width') >>> r.area 300.0 >>> r.width 10.0 >>> r.length 30.0 >>> # So far so good. Now why doesn't this work? >>> r.area = 500 >>> r.length 30.0 >>> r.length = 500 / r.width # this should have happened >>> r.length # giving this: 50.0 >>> # Example 2: another version that also doesn't work: >>> class Room: def __init__(self, width, length, fixed='length'): self.width = width self.length = length self.fixed = fixed self.__area = None def get_area(self): self.__area = self.width * self.length return self.__area def set_area(self, area): self.__area = area if self.fixed == 'length': self.width = self.__area / self.length if self.fixed == 'width': self.length = self.__area / self.width area = property(get_area, set_area, None, "Area of Room instance") >>> r = Room(10.0, 30.0, fixed='width') >>> r.area = 500 >>> r.length 30.0 Now what am I doing wrong here? Is it that I'm not supposed to change the value of another instance vars in a property set method? Do I have to write property set/get methods for 'length' and for 'width' then? Also another minor question: how does one get access to the doc string of the property? Thanks in advance, Sandy
- Previous message (by thread): Proper usage of properties in 2.2
- Next message (by thread): Vpython download problem
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
More information about the Python-list mailing list