[Edu-sig] Attribute Lookup Order

David MacQuigg macquigg at ece.arizona.edu
Fri Feb 6 20:32:35 CET 2009


>And I just noticed a great thread on comp.lang.python addressing the
>exact lookup order for obtaining attributes most recent post this
>morning.  The Thread Title is "Understanding  Descriptors",
>Brian Allen Vanderburg II asked the initial question, and Aahz and
>Bruno Desthuillers came up with a thorough answer.
>I'll put a link here, but it may wrap nastily.  Nickel summary, lookup
>order is not dirt simple, and reading and writing work differently.
>
>http://groups.google.com/group/comp.lang.python/browse_thread/thread/a136f7626b2a8b7d/70a672cf7448c68e

Maybe I'm missing some subtleties, but it still seems simple to me.  An attribute is looked up in the order object -> class -> superclasses, *UNLESS* that attribute happens to be a property of the class.  The purpose of properties is to over-ride direct access to attributes, and substitute your own getters and setters with whatever robustness is appropriate.  Say you have a 

class Rectangle(object):

    def __init__(self, width, height):
        self.width = width
        self.height = height
        self.area = width * height

and you find your students are changing the width and height parameters, but forgetting to change area.  The Java guys will say we should never have written such fragile code, but that is the beauty of Python.  We can write something simple, and add the robustness later.

class Rectangle(object):

    def __init__(self, width, height):
        self.width = width
        self.height = height
#        self.area = width * height

    def getArea(self):
        return self.width * self.height

    area = property(getArea)

Nothing in the interface changes.  Programs dependent on Rectangle will not break, unless they were setting area directly, which they should never have done.  Then when they do break, the user will see "AttributeError: can't set attribute", not some subtle error in the data that will screw up later usage.

The example is from Martelli's Nutshell, 2nd ed. p.100-101.  Quick summary (quoting Martelli): "The crucial importance of properties is that their existence makes it perfectly safe and indeed advisable for you to expose public data attributes as part of your class's public interface."

-- Dave 




More information about the Edu-sig mailing list