Class Variable Access and Assignment

Mike Meyer mwm at
Thu Nov 3 21:52:47 CET 2005

"Graham" < at> writes:
> I just seems to me that <instance>.<var> shouldn't defer to the class
> variable if
> an instance variable of the same name does not exists, it should, at
> least how i
> understand it raise an exception.
> Is my thinking way off here?

Yes. This behavior is how you get inheritted access to class
variables. Consider:

class Counter(object):
      "A mutable counter."
      # implementation elided

class A(object):
      instance_count = Counter()
      def __init__(self):

class B(A):
      instance_count = Counter()

This is sufficient to count instances of A and B. If
self.instance_count raised an exception, you'd have to do something
like A.instance_count in A.__init__, which would mean the __init__ B
inherited from A would do the wrong thing. Currently, you can either
reference class variables by explicit class, or via inheritance, and
both behaviors are desirable. If you're going to disallow
self.class_variable, you need to come up with a mechanism to replace
the latter behavior.

Mike Meyer <mwm at>
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.

More information about the Python-list mailing list