Python version 2.7.
Scenario
class A(object):
x = 0
class B(A):
pass
ai = A()
bi = B()
#Then:
id(ai.x) == id(bi.x)
>>> True
What I’d like to know is if there is a way, other than having all the class member definitions in __init__ to have instances of class B have their own copies of x without having to redefine them in class B?
Perhaps some type() tricks?
Haven’t found anything yet, but I’ll keep looking, figured here would be the best place to find an answer.
Any insight is greatly appreciated.
edit: grammars
edit2 To clarify as I didn’t really use the best example.
class Y(object):
def __init__(self):
self.z = 0
class A(object):
x = Y()
class B(A):
pass
ai = A()
bi = B()
id(ai.x) == id(bi.x)
>>> True
ai.x.z = 3
id(ai.x) == id(bi.x)
>>> True
Now the issue occurs that as I don’t reassign x in class B they both point to the same instance of class Y even if members of the instance of class Y change.
If you’re familiar with Django I’m almost recreating how their Forms work. I didn’t decide to go with a metaclass for the forms and then build up a dictionary of the fields everytime a new instance is created, perhaps I will need to switch to using a metaclass.
edit the third I’m realising now the impossibility I’m asking of the interpreter. As once I assign an instance of a class to a member there’s no way for the inherited classes to know how to create a new instance of that class. Therefore for my problem it seems metaclasses are the only solution.
For your example, it doesn’t matter with immutable objects.
bireferences a new object if it is ever assigned.Result:
Note also, that even if you initialize
xin__init__, that due to implementation-defined behavior, immutable objects can be cached and reused, and instancesaiandbistill share the0object.Result (with CPython 2.7.2):