Python create new object with the same value [duplicate]
I come from java world where I expect following things
int a = valueassignedbyfunction();
int b = a;
a = a + 1;
after this a is 1 greater than b. But in python the b automatically gets incremented by one once the a = a + 1 operation is done because this b is referencing to the same object as a does. How can I copy only the value of a and assig开发者_运维知识库n it to a new object called b?
Thanks!
Assuming integers, I cannot reproduce your issue:
>>> a = 1
>>> b = a
>>> a += 1
>>> a
2
>>> b
1
If we assume objects instead:
class Test(object):
... def __init__(self, v):
... self.v = v
...
>>> a = Test(1)
>>> b = a.v
>>> a.v += 1
>>> print a.v, b
2 1
# No issues so far
# Let's copy the object instead
>>> b = a
>>> a.v += 1
>>> print a.v, b.v
3 3
# Ah, there we go
# Using user252462's suggestion
>>> from copy import deepcopy
>>> b = deepcopy(a)
>>> a.v += 1
>>> print a.v, b.v
4 3
I think the main confusion here is the following: In Java, a line like
int i = 5;
allocates memory for an integer and associates the name i
with this memory location. You can somehow identify the name i
with this memory location and its type and call the whole thing "the integer variable i
".
In Python, the line
i = 5
evaluates the expression on the right hand side, which will yield a Python object (in this case, the expression is really simple and will yield the integer object 5
). The assignment statement makes the name i
point to that object, but the relation between the name and the object is a completely different one than in Java. Names are always just references to objects, and there may be many names referencing the same object or no name at all.
This documentation might help out: http://docs.python.org/library/copy.html
You can use the copy library to deepcopy objects:
import copy
b = copy.deepcopy(a)
I'm not sure what you're seeing here.
>>> a = 1
>>> b = a
>>> a = a + 1
>>> b
1
>>> a
2
>>> a is b
False
Python Integers are immutable, the + operation assigns creates a new object with value a+1. There are some weird reference issues with integers (http://distilledb.com/blog/archives/date/2009/06/18/python-gotcha-integer-equality.page), but you should get the same thing you expected in Java
How about just doing
a = 1
b = a*1
精彩评论