-2

Let's assume 2 files :

main.py

from TestClass import TestClass

testObj_1 = TestClass("obj_1")
testObj_2 = TestClass("obj_2")

print(id(testObj_1.m_data_0))
print(id(testObj_2.m_data_0))
print(id(testObj_1.m_data_1))
print(id(testObj_2.m_data_1))

and

TestClass.py

TEST_LENGTH = 5

class TestClass:
    """TestClass."""

    def __init__(self, name, data_0 = [0] * TEST_LENGTH, data_1 = 5):
        """Constructor."""
        self.m_name = name
        self.m_data_0 = data_0
        self.m_data_1 = data_1

Running the code returns

1795863465536
1795863465536
140720295764904
140720295764904

Which means the member variables that were initialised by a default value argument all point to the same data (and thus updating the member variable for an object udates the value for all objets, as all object share the same memory).

I know that the variables are only references to a data, but I do not understand why python does not instantiate a new default value data for each call to the __init__ function. How can I initialize with a function default argument without having the object share the data?

Barmar
  • 741,623
  • 53
  • 500
  • 612
arennuit
  • 855
  • 1
  • 7
  • 23

0 Answers0