pythonclassoopheap-memory

Class not creating new instances upon repeated calls


May be I am missing something really basic here, but when I define a class in the following manner:

class Arbitrary(object):
    """Arbitary class to test init"""
    def __init__(self):
        self.x = dict()

and repeatedly instantiate the class in the following way

for i in range(5):
    a = Arbitrary()
    print '{}  {}  {}  {}'.format(i, a, id(a), a.x)

I am not getting totally new instances of Arbitrary() class as I expect it to. In fact, I am getting repetition of two instances:

0  <__main__.Arbitrary object at 0x1006cb110>  4302090512  {}
1  <__main__.Arbitrary object at 0x1006cb190>  4302090640  {}
2  <__main__.Arbitrary object at 0x1006cb110>  4302090512  {}
3  <__main__.Arbitrary object at 0x1006cb190>  4302090640  {}
4  <__main__.Arbitrary object at 0x1006cb110>  4302090512  {}

Why is that?

How can I define the __init__ in my class such that every new call to Arbitrary() would return a totally new instance?


Solution

  • I'm not a Python expert but I can see you are overwriting your instances. I tried changing it to below and it runs ok :

    #!/bin/env python
    
    class Arbitrary(object):
        """Arbitary class to test init"""
        def __init__(self):
            self.x = dict()
    
    a = []
    for i in range(5):
        a.append(Arbitrary())
        print '{}  {}  {}  {}'.format(i, a[i], id(a[i]), a[i].x)
    

    result :

    ckim@stph45:~/python/test2] test2.py
    0  <__main__.Arbitrary object at 0x7fc6952b6090>  140490882900112  {}
    1  <__main__.Arbitrary object at 0x7fc6952b6250>  140490882900560  {}
    2  <__main__.Arbitrary object at 0x7fc6952b6290>  140490882900624  {}
    3  <__main__.Arbitrary object at 0x7fc6952b62d0>  140490882900688  {}
    4  <__main__.Arbitrary object at 0x7fc6952b6310>  140490882900752  {}