[Tutor] Need help with the property function

Steven D'Aprano steve at pearwood.info
Thu Apr 14 01:18:18 CEST 2011


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

What's Dawson's book?


> 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]

This defines a read/write property. You can read it, and write to it.

>     # name = property(get_name) #[2]

This, uncommented out, defines a read-only property. You can't write to it.


>     #different_name = property(get_name) #[3]

Uncommented out, this defines a read-only property, but you don't get 
any errors because nowhere in your code do you try to write to it.


>     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


That's because you're trying to write to a read-only property inside the 
__init__ method with the line "self.name = name".


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

Until you do this:

crit = Critter("Poochie")
crit.different_name = "Itchy"


and then you will see the same error.




The property function takes at least one, and at most four, arguments:


name = property(getter, setter, deleter, docstring)


"getter" must be a method that tells the class what to do when the 
caller *reads* the attribute with "instance.name".

If present, "setter" must be a method that tells the class what to do 
when the caller *writes* the attribute with "instance.name = value". If 
there is no setter, you can't write to the attribute.

If present, "deleter" must be a method that tells the class what to do 
when the caller *deletes* the attribute with "del instance.name". If 
there's no deleter, you can't delete the attribute.

And finally, "docstring", if present, needs to be a text string which is 
used, well, it's never actually used anywhere, but you can find it if 
you look for it. It's just a message to anyone reading it. docstring is 
short for "documentation string".




-- 
Steven



More information about the Tutor mailing list