Class Variable Access and Assignment
Mike Meyer
mwm at mired.org
Thu Nov 3 15:52:47 EST 2005
"Graham" <graham.abbott at gmail.com> 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):
self.instance_count.increment()
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
--
Mike Meyer <mwm at mired.org> http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.
More information about the Python-list
mailing list