need help with properties

Esmail ebonak at hotmail.com
Sat May 9 17:30:02 CEST 2009


Hi,

I am just reading about properties in Python. I am thinking
of this as an indirection mechanism, is that wrong? If so, how
come the getter/setters aren't called when I use properties
instead of the functions directly?

What am I missing here? I have a feeling I am overlooking
something simple here...

Thanks,
Esmail

---
#!/usr/bin/env python

#
# quick test to deal with 'private' attributes and
# python properties ...
#

import sys

class Rectangle(object):

     def __init__(self):
         self.__width = 0
         self.__height = 0


     def setSize(self, width, height):
         print 'in setter'
         if (width < 0) or (height < 0):
             print >> sys.stderr, 'Negative values not allowed'
         else:
             self.__width = width
             self.__height = height


     def getSize(self):
         print 'in getter'
         return self.__width, self.__height


     size = property(getSize, setSize)

r = Rectangle()
print r.getSize()
r.setSize(-40, 30)
print r.getSize()

print '-----------------'
size = 3, 7
print size

print '-----------------'
size = -3,7
print size



The program output:


in getter
(0, 0)
in setter
Negative values not allowed
in getter
(0, 0)
-----------------
(3, 7)
-----------------
(-3, 7)




More information about the Python-list mailing list