[Tutor] set/getattr and inheritance

Kirby Urner urnerk@qwest.net
Sat, 06 Oct 2001 11:21:13 -0700


Note:  starting with Python 2.2, there's a whole other way
to define set and get methods, using the new builtin 'property'.

Here's an example, based on the example given in the tutorial
at http://www.python.org/2.2/descrintro.html#property (itself
nothing more than an example):

  >>> class C(object):

        def __init__(self):
	    self.__x = None
	    self.__y = None
	
	def getx(self):
	    return self.__x
	
	def setx(self,val):
	    if not str(val) in string.uppercase:
		print "Nope"
	    else: self.__x = val
		
	def gety(self):
	    return self.__y
	
	def sety(self,val):
	    if not str(val) in string.digits:
		print "Nope"
	    else: self.__y = val
	
	x = property(getx, setx)
	y = property(gety, sety)

	
  >>> o = C()
  >>> o.y = 1
  >>> o.y
  1
  >>> o.y = 'A'
  Nope
  >>> o.x = 'a'
  Nope
  >>> o.x = 'A'
  >>> o.x
  'A'

Kirby