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
--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to