[Tutor] when to use properties?

Marcus Goldfish magoldfish at gmail.com
Tue Apr 12 22:20:58 CEST 2005


Are there guidelines for when properties should be used vs. instance
variables?  For example, it often seems more convenient to directly
use instance variables instead of properties, like MyClass2 listed
below.  Is one class more pythonic than the other?

# Example 1: class w/props vs. no-propt
class MyClass1(object):
  def __init__(self, value=0):
     self._value = value
  def getValue(self):
     return self._value
  def setValue(self, value):
     self._value = value
  value = property(getValue, setValue)

class MyClass2(object):
  def __init__(self, value=0):
     self.value = value

x1 = MyClass1(3)
x1.value = 3

# same as this?
x2 = MyClass2(3)
x2.value = 3

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?

Marcus


More information about the Tutor mailing list