If I do this, I get:
>>> x = 1
>>> y = '2'
>>> type(x)
<class 'int'>
>>> type(y)
<class 'str'>
That all makes sense to me, except that if I convert using:
>>> str(x)
'1'
>>> type(x)
<class 'int'>
>>> int(y)
2
>>> type(y)
<class 'str'>
...why are my types only temporarily converted, i.e. why despite str(x) and int(y) is x still an integer and y is still a string?
Do I have to replace x and y to make type permanent with:
>>> x = '1'
>>> y = 2
>>> type(x)
<class 'str'>
>>> type(y)
<class 'int'>
I can see how it's useful to have the type of a variable permanently fixed, but as a new coder it's good to know what I'm contending with.
答案 0 :(得分:3)
str(X)
and int(X)
are returning a new object/value of a given parameter.
If you want to change the typ of a variable then you need to safe the new outcoming object like this:
x = 1
x = str(x)
type(x)
>> <class 'str'>
答案 1 :(得分:1)
This is because you're dealing with a new object. In fact if something is a str
, str(obj)
returns the object, otherwise str(obj)
returns a str
representing an objects __str__
method, while int
returns a reference to the int
in memory. You can see this by using python's id
function, which tracks references to objects:
>>> f = 1
>>> id(f)
4297148528 # your IDs will be different.
>>> g = f
>>> id(g) # all ints share the same ID
4297148528
>>> g = '1'
>>> id(g)
4301500520 # a str of the same value is a different ID
>>> id(int(g))
4297148528 # this is the same int
>>> g
'1' # value at g hasn't changed
>>> h = g
>>> id(h)
4301500520 # if you assign a value to a new variable, then you get the same ID
>>> h = int(g) # now cast it back to an int
>>> id(h)
4297148528