Reputation: 23567
I am a bit confused on how object values persist in python.
Let say I have an class object a
that has a specific set of attributes attached to it. Multiple classes B
, C
have their own references to class a
when each of them are created. Only class C
can modify stuff in class a
. When it is modified, does class B
pick them up? From creating my own example they seem to do so.
My question is are there any instances where I should be aware of when changes to wont be picked up? When does python create an copy of class a
? More specifically, what will create a copy of it that wont affect the original a
.
class A:
def __init__(self):
self.x = 1
def changeX(self,num):
self.x = num
class B:
def __init__(self,classA):
self.x = classA
class C:
def __init__(self,classA):
self.x = classA
def ChangeA(self,num):
self.x.changeX(num)
c_a = A()
c_b = B(c_a)
c_c = C(c_a)
c_c.ChangeA(2)
# All returns 2
c_a.x
c_b.x.x
c_c.x.x
Upvotes: 2
Views: 120
Reputation: 560
Assignment statements in Python don't copy objects, they create bindings between the target and an object.
An easy to understand guide on how this different from other languages is available here.
When you need to change an assigned object so it does not affect other assigned objects you can use the copy
module. (https://docs.python.org/3.4/library/copy.html)
import copy
class A:
def __init__(self):
self.x = 1
def changeX(self,num):
self.x = num
class B:
def __init__(self,classA):
self.x = classA
class C:
def __init__(self,classA):
self.x = classA
def ChangeA(self,num):
self.x.changeX(num)
c_a = A()
c_b = B(c_a)
c_c = copy.deepcopy(C(c_a))
c_c.ChangeA(2)
c_a.x #1
c_b.x.x #1
c_c.x.x #2
Upvotes: 1
Reputation: 122366
Unless you create a copy Python won't create a copy for you. You can use the copy
module to create copies of objects or you can create a new object with the same values.
In your example there is only once instance of class A
and each of the c_a
, c_b
and c_c
have access to it. That's why you're seeing 2
in each case as they're all the same attribute on the same object.
Upvotes: 1