I'm wondering what the difference between the following two snippets of code is:
float_var = 1234.5678
a = int(float_var)
b = (int)(float_var)
They both successfully convert the variable to an integer (at least in Python 3.6, I don't know if this behaviour is supported in 2.7) but there's an obvious difference in syntax. Furthermore, the following snippet fails:
c = (int)float_var
Which leads me to believe that the variable name (or literal, as it may be) must be enclosed in parentheses.
From what I can gather the difference in the two examples is that the first one creates a new instance of a class by passing a parameter into its __init__ method. Whereas in the second example, since the int object defines a method __float__, it can "cast" any float to an instance of int.
Am I correct in thinking this? Also, why does the third example fail? I don't understand why parentheses are required to surround the value being "cast".
aandbare identical.intsimply do nothing. You could use thedismodule to look at the the resultant bytecode it will be the same.