[Tutor] when to use properties?

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Tue Apr 12 23:22:23 CEST 2005



On Tue, 12 Apr 2005, Marcus Goldfish wrote:

> Are there guidelines for when properties should be used vs. instance
> variables?

Hi Marcus,


In Python, it's easy to modify things so that things that look like
instance variable access are automatically shunted off to do programatic
stuff.

In Python, I'd go with the simple instance variable stuff, since it's easy
to go back and turn something into a property when you need it.  Go with
instance variables first.

There was an interesting article by Phillip Eby about what conventions
work and don't work when one makes a jump from Java to Python:

    http://dirtsimple.org/2004/12/python-is-not-java.html



> On the other hand, I can see how classes that dynamically generate
> "properties" might find the construct convenient:
>
> # Example 2: properties "on-the-fly"
> import math
> class RightTriangle(object):
>   def __init__ (self, a=3, b=4):
>      self.a = a
>      self.b = b
>   def getHypotenuse(self):
>      return sqrt(a**2 + b**2)
>   hypotenuse = property(getHypotenuse)
>
> t = RightTriangle()
> t.hypotenuse         # returns 5.0
>
> But in Example2 it's still not clear to me whether properties buy
> anything-- why not just use the getter function?

Here, it's just pure syntactic sugar.  There's nothing functionally
different at all: it's just how it reads.  So, we really aren't getting
anything.  But I wouldn't discount syntax outright:  people read programs
just as much as computers execute them.

in the case when we're defining a setter, we may want the assignment to
stand out syntactically, since mutation is always a bit scary.  *grin*

That is, something like:

    money.amount = 16

stands out more as an mutation --- an assignment --- and has a higher
chance to catch the human reader's eye.  The setter method:

    money.setAmount(16)

might be easier to overlook on a visual scan, since the setter is just
another method call in what could be a page full of method calls.


That being said, I personally haven't used properties in my own code, only
because it confuses my friends who are still used to languages like Java,
where Java doesn't allow one to overload attribute access.  Properties
appear to make Python syntax a little more distinctive.

Best of wishes!



More information about the Tutor mailing list