Reputation: 1137
I known if I want to do type conversion in Python, I should use the built-in functions.
for example:
number = int('100')
but I am using c# style to do conversion like
number = (int)('100')
it also work, could you tell me why that is working.
and if I try to do the same thing using the code below, it does not work.
number = (int)'100'
Upvotes: 2
Views: 113
Reputation: 61635
int('100')
This means "find the object named int
, and call it as a function, passing '100'
as an argument".
(int)('100')
This means the same thing, since the left-hand-side is now (int)
, which is the same as int
, for the same reason that (3)
is the same as 3
.
(int)'100'
By the same principle, this is the same as int '100'
, which is a syntax error: you have two objects - the int
class, and the string '100'
- next to each other, with no operator or other indication of how they are supposed to interact.
Upvotes: 2
Reputation: 4818
In python functions are first class objects, so int
and (int)
are actually the same object, the built-in function int.
>>> a = (int)
>>> a('100')
100
>>> a is int
True
You can call a function as in the example above, but not use it as a cast, c-style.
Upvotes: 0
Reputation: 2898
In python "int" is a class and calling "int('100')" calls the __init__ method of the int class with the argument '100'. This constructs an int object.
The expression "(int)" is no different than "int". Python has no casting/conversion operators like some other languages.
Upvotes: 0
Reputation: 7048
Apart from when specifying function arguments, (x)
is the same as x
, so (int)('100')
is equivalent to int('100')
.
They even compile to the same bytecode:
>>> import dis
>>> dis.dis(lambda: int('100'))
1 0 LOAD_GLOBAL 0 (int)
3 LOAD_CONST 1 ('100')
6 CALL_FUNCTION 1
9 RETURN_VALUE
>>> dis.dis(lambda: (int)('100'))
1 0 LOAD_GLOBAL 0 (int)
3 LOAD_CONST 1 ('100')
6 CALL_FUNCTION 1
9 RETURN_VALUE
Upvotes: 4
Reputation: 799240
Python doesn't have "type conversion"; you are passing '100'
to the int
constructor. Putting parens around the type does not change its value, but removing the parens from the type's argument means that it's no longer a constructor call but rather a syntax error.
Upvotes: 6