Bug or feature?

Tim Peters tim_one at email.msn.com
Sat May 15 03:50:46 EDT 1999


[Gregory A. Landrum]
> ...
> So I figured I could initialize things which are going to have
> default values outside of the __init__ method and thus (I thought)
> make the code a little bit easier to read.

Oh, you can!  This is all simpler than it looks <wink>, it's just
*different*.  The simple rules are:

    access class data via ClassName.dataname
    access instance data via self.dataname
    as always, mutate with care

One possibly overused trick in some Python code is to combine the two, like
so:

class HasLotsOfAttributesUsuallyTheSame:
    # default values for instances
    color = "red"
    xcoord = 0
    ycoord = 10
    name = None
    children = []
    parents = []
    url = "http://www.python.org/"

    # class data
    allparents = []

    def __init__(self, parent=None, color=None):
        if color is not None:
            self.color = color  # creates an instance attr named "color"
        if parent is not None:
            self.parents = [parent]  # creates an instance attr likewise
            # self.parents.append(parent) is a bad idea!
            if parent not in HasLotsOfAttributesUsuallyTheSame.allparents:
                HasLotsOfAttributesUsuallyTheSame.allparents.append(parent)

Create a million of these guys x, and all of them will have x.xcoord == 0,
but without consuming storage for a million "xcoord" keys in a million
instance dicts -- they all share the single xcoord/0 key/value pair in the
*class* dict.  OTOH, an explicit assignment to self.xcoord within a method
will create a non-shared attr for self, allowing that particular self to
break free of the class's default xcoord value at the cost of consuming more
storage.

As Donn Cave said, the issues here are very much akin to local vs global
data bindings in Python; and the true nature of a thing lies not in where or
how it's spelled, but in how it's used.

Once the rules are grasped, class data in Python is easy to use and more
flexible than in e.g. C++.  So-called class *methods* are a different story,
for one telling of which see the FAQ.

render-unto-the-class-that-which-is-the-class's-and-keep-your-fingers-
    to-your-self-ly y'rs  - tim






More information about the Python-list mailing list