Class variable inheritance

Henry 'Pi' James henrypijames at gmail.com
Mon Sep 7 22:21:28 EDT 2009


I've just found out that a subclass shares the class variables of its
superclass until it's instantiated for the first time, but not any
more afterwards:

Python 3.1 (r31:73574, Jun 26 2009, 20:21:35) [MSC v.1500 32 bit
(Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> class A:
...   n = 0
...   def __init__(self):
...     type(self).n += 1
>>> class B(A):
...   pass
>>> A.n, B.n
(0, 0)
>>> (A().n, A.n, B.n), (A().n, A.n, B.n), (B().n, A.n, B.n)
((1, 1, 1), (2, 2, 2), (3, 2, 3))
>>> (A().n, A.n, B.n), (A().n, A.n, B.n), (B().n, A.n, B.n)
((3, 3, 3), (4, 4, 3), (4, 4, 4))
>>> (A().n, A.n, B.n), (A().n, A.n, B.n), (B().n, A.n, B.n)
((5, 5, 4), (6, 6, 4), (5, 6, 5))

This makes no sense to me at all. Could it possibly be a bug?



More information about the Python-list mailing list