0

Why does python return the same instance of class Config in this situation?

class Config():
    pass

class A():
    def builder(self):
        return Config()

class B(A):
    def get_config(self):
        return self.builder()

class C(A):
    def get_config(self):
        return self.builder()

def main():
    b = B()
    c = C()

    print(b.get_config())
    print(c.get_config())

    a1 = A()
    a2 = A()

    print(a1)
    print(a2)

    print(a1.builder())
    print(a2.builder())

if __name__ == "__main__":
    main()

Output:

$ python3 main.py
<__main__.Config object at 0x7fd96cd850a0>
<__main__.Config object at 0x7fd96cd850a0>

<__main__.A object at 0x7fd96cd850a0>
<__main__.A object at 0x7fd96cd85370>

<__main__.Config object at 0x7fd96cd856a0>
<__main__.Config object at 0x7fd96cd856a0>

I was expecting that because B and C are different classes, when I call get_config() method, the returning instance of Config would not be the same object in both cases.

The same happens when I create two instances of class A and directly calls the method builder(). As we can see on the output, a1 and a2 are clear distinct objects, but why does the return of a1.builder() is the same Config() instance of a2.builder()?

  • After objects are discarded their ids are eligible for reuse. Just because they reuse the same id doesn't mean they are the same object. – khelwood Feb 16 '22 at 21:53
  • Assign the results of `get_config()` to variables so the memory isn't reused each time. – Barmar Feb 16 '22 at 21:55
  • But why and how does python reuses this memory address even though the parent classes creating Config() are completely different? – Marco Antonio Silveira Feb 16 '22 at 22:10

0 Answers0