0

I am using python to implement an application. I have following classes:

class A():
    def __init__(self):
        self._B_list=[]    # objects of B class will be appended as the application run
        b = B(self)        # I use A as initial parameter of B
        self._B_list.append(b)


class B()
    def __init__(self, A_object):
        self._parent = A_object      # Here I save the pointer of upper layer class object

As you can see from above, class A has a list of objects of class B. And B will record its upper layer object. The reason I do this is because there is a big data container (20 MB) in class A, and it should be shared by all the class B objects in its list.

I think the way I showed above is memory effective. But since I've never been formally traind to code Python, I am not very sure about this. So may I have you opinion? Any comments are welcome.

Thanks.

ChangeMyName
  • 7,018
  • 14
  • 56
  • 93

1 Answers1

2

Since there is only one A, you don't need to store a pointer to it in every single instance of B. Once this OnlyOneA is created, just assign it to the class B and every instance of B will find it:

class A(): 
    def __init__(self):
        assert(not hasattr(B, '_parent')) # make sure there is only one A
        B._parent = self
        ...

then if myB is an instance of B

my._parent

will get the instance of A.

hivert
  • 10,579
  • 3
  • 31
  • 56
  • Hi, hivert. Thanks for the answer. Sounds very reasonable. On the other hand, may I know what is the memory usage in my way? Will the `OnlyOneA` be duplicated for each `B` and practically occupy a memory block? – ChangeMyName Feb 04 '14 at 12:00
  • 1
    No it won't. It's only stored in the class as a reference (no copy). It's called a *class attribute* – hivert Feb 04 '14 at 12:07