[Tutor] Need help with the property function

Jim Byrnes jf_byrnes at comcast.net
Wed Apr 13 22:33:42 CEST 2011


I'm trying to teach myself OOP in python (again). The following code 
from Dawson's book runs fine, unaltered [1].

class Critter(object):
	""" A virtual pet """
	def __init__(self, name):
		print "A new critter is born"
		self.name = name
		
	def get_name(self):
		return self.__name
	
	def set_name(self, new_name):
		if new_name == "":
			print "A critters name cant be the empty string"
		else:
			self.__name = new_name
			print "Name change successful"	

			
	name = property(get_name, set_name) #[1]
	# name = property(get_name) #[2]
	#different_name = property(get_name) #[3]

	def talk(self):
		print "Hi. I'm", self.name

If I change [1] to [2] I get:

Traceback (most recent call last):
   File "propertycritter.py", line 26, in <module>
     crit = Critter("Poochie")
   File "propertycritter.py", line 7, in __init__
     self.name = name
AttributeError: can't set attribute

If I change [1] to [3] the program runs with no errors.

Could someone please explain why I am seeing these results.

Thanks,  Jim


More information about the Tutor mailing list