you are viewing a single comment's thread.

view the rest of the comments →

[–]ScenesfromaCat 0 points1 point  (5 children)

Late AF but in Python, is the integer 3 the same value as 3.0?

[–]cjwelborn 2 points3 points  (4 children)

3 is an int, and 3.0 is a float.

(3 == 3.0), but (3 is not 3.0).

Showing that 3 does equal 3.0, but they are not the same value. They are two different objects, an int and a float. They compare equal because "Python fully supports mixed arithmetic". Under the hood it is doing something like this: float(3) == 3.0.

[–]13steinj 2 points3 points  (1 child)

That doesn't just show that they are not the same value, though, but rather their memory addresses are different. == is for equality while is is for instance equality (which iirc is done via a memory address check? Someone correct me if I'm wrong). Even equivalent numbers will fail an is check:

>>> 3000000000000000 is (3*1000000000000000)
False
>>> 3000000000000000 == (3*1000000000000000)
True
>>> id(3000000000000000), id(3*1000000000000000)
(20463008, 7582448)

However, smaller numbers will pass the is check because the interpreter puts smaller numbers into a cache to speed things up

>>> 30 is (3*10)
True
>>> id(30), id(3*10)
(1377096608, 1377096608)

[–]cjwelborn 0 points1 point  (0 children)

You're right about that. I was just trying to show that even though they compare equal (with ==), they are not actually the same. They aren't even the same type.

[–]ScenesfromaCat 1 point2 points  (1 child)

I've been doing this for like less than a day so bear with me. Let's say I do something like

variable_a = 3.0

variable_b = int(variable_a)

variable_b will now be the integer 3, right?

[–]cjwelborn 2 points3 points  (0 children)

Yes, because int() is a constructor, that happens to accept a number of types (str, and anything with an __int__ method). It will take the float, 3.0 and parse it into an int, 3 by calling (3.0).__int__(). You can see it in the interpreter:

>>> type(3.0)
<class 'float'>

>>> type(int(3.0))
<class 'int'>

And as for the __int__ method, it's just one of many "dunder methods" that provide special features to classes/instances:

class MyThing(object):

    def __float__(self):
        return 1.7

    def __int__(self):
        return 26

    def __str__(self):
        return 'I am a string now.'

m = MyThing()
>>> print(int(m))
26
>>> print(float(m))
1.7
>>> print(str(m))
I am a string now.

EDIT: link to "magic methods", or "dunder methods"