Class Variable Inheritance

Steven Bethard steven.bethard at gmail.com
Wed Dec 8 22:55:40 EST 2004


Brian "bojo" Jones wrote:
> It became clear to me that mastervar inside of class a is a static 
> variable, and is associated with all instances of classes that extend 
> class a.

Yeah, that's basically what's happening.  AFAICT, a variable declared at 
class level is shared with all subclasses (and is available to all 
instances unless hidden by an instance variable).  You can simulate the 
kind of behavior you want using descriptors:

 >>> import copy
 >>> class subclass_copied(object):
...     def __init__(self, initial_value):
...         self.initial_value = initial_value
...         self.instances = {}
...     def __get__(self, instance, owner):
...         if owner not in self.instances:
...             self.instances[owner] = copy.copy(self.initial_value)
...         return self.instances[owner]
...
 >>> class A(object):
... 	x = subclass_copied([])
...
 >>> class B(A):
... 	pass
...
 >>> A.x.append(1)
 >>> A().x.append(2)
 >>> A.x
[1, 2]
 >>> B.x
[]
 >>> B.x.append(3)
 >>> B().x.append(4)
 >>> B.x
[3, 4]
 >>> A.x
[1, 2]

Basically, the subclass_copied descriptor returns a different object for 
each class by keeping a type -> object dict.  If you wanted to be 
thorough with this, you would probably define a __set__ method too; see:

http://docs.python.org/ref/descriptors.html

Steve

Steve



More information about the Python-list mailing list