For this code when I change x
to k
using change()
and then call self.co
it does not return the updated value of self.x
. How do I fix this kind of problem generally (this is a basic example)?
class scope:
tag=1
def __init__(self,h,x):
self.h = h
self.x = x
self.co=(self.x,self.h)
def change(self,k):
self.x=k
You did not change the self.co attribute
. You are assigning to self.co
only when initialization of scope
occurs, that is, when you call scope()
.Also Python doesn't keep references like pointers in c so changing one would not change the other.
To prove this run this code:
class scope:
tag=1
def __init__(self,h,x):
self.h = h
self.x = x
self.co=(self.x,self.h)
def change(self,k):
self.x=k
s = scope(2,3)
print(s.co)
print("id of self.x before change:", id(s.x)) #11161896
print("id of self.co's x before change:", id(s.co[0])) #11161896
s.change(6)
print(s.co)
print("id of self.x after change:", id(s.x)) #11161824
print("id of self.co's x after change:", id(s.co[0])) #11161896
The id are the memory location of the object, and you can see it first starts out the same, but then when you change self.x
the memory location in the co
doesn't change
You have to update self.co
in your change()
. If you want a dynamically changing co without manually updating it, write a method to retrieve co.
Option 1:
class scope:
tag=1
def __init__(self,h,x):
self.h = h
self.x = x
self.co=(self.x,self.h)
def change(self,k):
self.x=k
self.co = (self.x,self.h)
Option 2:
class scope:
tag=1
def __init__(self,h,x):
self.h = h
self.x = x
def change(self,k):
self.x=k
def co(self):
return (self.x,self.h)
s = scope(2,3)
print(s.co()) #(3,2)
s.change(6)
print(s.co()) #(6,2)
You can add to method 2 with a decorator @property
to not make it a function call but at this point, I have no idea what your requirements are.