Paul
Paul

Reputation: 982

How does python instantiate attributes when new class is created with attribute of existing class?

I have a simple Point class with attributes z, y and z. I first instantiate the first object:

point1 = Point(1, 2, 3)

Now I instantiate my second point like this:

point2 = Point(point1.x, 3, 4)

When I run id() on the points and attributes I get this

id(point1): 1565146411848: x: 1, y: 2, z: 3 id(point1.x): 140711867415616
id(point2): 1565146435400: x: 1, y: 3, z: 4 id(point2.x): 140711867415616

Clearly the two Point objects are unique, however, they seem to share the same x.

Now, when I change, say point2.x = 900, the following happens:

id(point1): 1565146411848: x: 1, y: 2, z: 3 id(point1.x): 140711867415616
id(point2): 1565146435400: x: 900, y: 3, z: 4 id(point2.x): 1565143647248

point2.x is now differnent to point1.x. So I assume at the point of assignment under these conditions, a new instance of the attribute x is created? I am not clear what the rules of python is here, I have always understood that assignment does not cause instantiation, however it would appear as though this is exactly what happens here? How does this work?

Upvotes: 1

Views: 217

Answers (1)

Hammerite
Hammerite

Reputation: 22340

Python variables - this includes members of objects and things like list and dictionary elements - are references to values. When you create point2 passing in point1.x as the x-value, you get a new reference to the same value. That's why it has the same id.

In this case it really doesn't matter much because integers are immutable. It could matter if your x was a mutable object like a list. Try that and see what happens when you change the list through either object's x-reference (you'll see changes made through one variable affect the other).

There is another slight complication in understanding this behaviour in the case of integers, in that CPython "interns" small integers. That is, every reference to the integer 1 ends up being a reference to the same copy of 1. Try repeating your experiment but passing in literally 1 instead of point1.x and you will see what I mean.

Upvotes: 1

Related Questions