0

I would like to know if there's a way that we can instantiate a class only once when called from one of the child class and somehow cache it and use it for second child class without instantiating the parent class.

class A:
   def __init__(self):
      #some huge data stored in self parameters.
class B:
   def __init__(self):
      A.__init__(self)
class C:
   def __init__(self):
      A.__init(self)

So both classes B and C uses class A as a parent class and class A has huge data initialised which can be used by both classes B and C. So what I'm trying to achieve here is when I instantiate class B for example, it instantiates class A and loads all the data into memory and to cache the instance so when I immediately instantiate class C it looks for the existing instance of the class without instantiating it again.

  • Use singleton approach it ensures to create heavy objects only once and stores in memory as one object and whenever wants it just call it ,search for singleton in python – Ali Nour Aug 20 '21 at 15:45
  • Does this answer your question? [Is there a simple, elegant way to define singletons?](https://stackoverflow.com/questions/31875/is-there-a-simple-elegant-way-to-define-singletons) or perhaps https://stackoverflow.com/questions/6760685/creating-a-singleton-in-python – JonSG Aug 20 '21 at 15:49

1 Answers1

0

How about instantiating A in B and providing a method to transfer the data from B to outside? See below:


class A:
   def __init__(self):
      self.huge_data = [.....]

   def data(self):
      return self.huge_data

class B:
   def __init__(self):
      self.a = A()

   def pass_data(self)
      return a.data()

class C:
   def __init__(self):
      A.__init(self)

Once you instantiate B, you will be able to use the method to access the data.

ilpianoforte
  • 1,180
  • 1
  • 10
  • 28