Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading