Persistence Of Objects In Python
Solution 1:
You don't understand python. You need to understand variables (almost everything in python is basically a pointer), and namespaces.
OK, so you don't understand when python creates new objects.
In 90% of cases, every time you see an object, it will be a new one.
For example:
a = [1,2,3]
b = a + [4,5]
print a
>>> [1,2,3]
See? b is a new object, a is untouched.
Also:
def func(a):
a = [1,2,3]+a
return a
a = [4,5]
print func(a)
>>> [1,2,3,4,5]
print a
>>> [4,5]
Why did this happen? Inside the function, there's a whole new namespace (which is probably something like a new stack). So the new a
inside the function has nothing to do with the old a
outside the function.
It's really hard to make python share data, which makes it really hard for one section of code to mess with variables in another area.
You can alter stuff, but you have to jump through hoops:
def func(a):
a.append([4,5])
return a
a = [1,2,3]
print func(a)
>>> [1,2,3,4,5]
print a
>>> [1,2,3,4,5]
See, it worked! I altered a
, because I used a method of a, not creating a new variable.
Post a Comment for "Persistence Of Objects In Python"