[Tutor] Need help with the property function

Jim Byrnes jf_byrnes at comcast.net
Thu Apr 14 16:12:33 CEST 2011


Dave Angel wrote:
> On 01/-10/-28163 02:59 PM, Jim Byrnes wrote:
>> 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
>>
>
> In case#2 you're making name a read-only property. So why on earth would
> you expect to be able to modify that property?
>
> DaveA
>
>

Because I was confused and didn't fully understand the process.  I was 
experimenting and trying understand it to use it something else I was 
writing.

Regards,  Jim


More information about the Tutor mailing list