Why is the floating-point variable of the subclass the same memory address as the floating-point variable of the parent class?

Question:

As shown in the code, a parent class ClassA is established, which has a variable var1, and a subclass ClassB inherits the parent class, which has a variable var2. As a result, the addresses of var1 and var2 are the same, why is this?

As a result, whether I assign a value to var1 or var2, the value of both is the same. What is the reason for this?

My code is as follows:

class ClassA:
    def __init__(self):
        self.var1: float = 0


class ClassB(ClassA):
    def __init__(self):
        super(ClassB, self).__init__()
        self.var2: float = 0
        print(id(self.var1) == id(self.var2))


a = ClassB()

The result I get:

True

My expected result:

False

Tried many times, only this can achieve my goal:

class ClassA:
    def __init__(self):
        self.var1: float = float('nan')


class ClassB(ClassA):
    def __init__(self):
        super(ClassB, self).__init__()
        self.var2: float = float('nan')
        print(id(self.var1) == id(self.var2))


a = ClassB()

False
Asked By: jaried

||

Answers:

It’s due to how python handle the memory, for some immutable types such as integer or string there are some values that are "common" and cached by python, then when you try to use the same value some other place the cached value is used making it the same address.

The 0 is part of the integers values that are cached by python, so in your case the addresses are the sames.

And yes your value is an integer even if you declare it as a float, the only thing this do is to check if the value match a float and 0 match a float even if it’s an int.

You can verify this with

>>> a:float = 0
>>> a
0
>>> type(a)
<class 'int'>
>>>
>>> b:float = 0.0
>>> b
0.0
>>> type(b)
<class 'float'>
>>>

For more details I suggest you take a look at this answer

Answered By: Xiidref
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.