0

I have two classes that inherit from the same base class. In the base class I have a very expensive method that must be ran only once and whose generated attributes must be available to the child class. How do I achieve that?

In the example below, the instantiation of the B and C child classes will both run expensive_op in A. I'd like expensive_op to be called only when I call b=B(). A is never called directly.

Moreover, I want to be able to modify the attributes of the parent class from the child class as done, for example, in the modify method in B.

Anyone able to help?

class A:
  def __init__(self):
    self.expensive_op()
  def expensive_op(self):
    self.something = #something ugly and expensive

class B(A):
  def __init__(self):
    super().__init__()
  def modify(self,mod):
    self.something = self.something+mod

class C(A):
  def __init__(self):
    super().__init__()
    
b = B()
c = C()

EDIT: in response to @0x5453's comment, do you mean the modification of A below?

class A:
  def __init__(self):
    self.something = None
  def expensive_op(self):
    if self.something is not None:
      self.something = #something ugly and expensive

But if I call b=B() and then c=C(), the latter won't know about self.something. The output is

b=B()
c=C()
b.expensive_op(3)
print(b.something)
>>> 3
print(c.something is None)
>>> True

Am I missing something?

mdurant
  • 27,272
  • 5
  • 45
  • 74
lorenzo_
  • 11
  • 2
  • 1
    You can turn `self.something` into a class attribute of `A`, so that its value will be shared among all instances of `A` (which includes children of `A`). Default it to `None` and then only run `expensive_op` if `something is None`. – 0x5453 Aug 15 '22 at 13:55
  • Are you averse to directly calling the parent class in the children, like `A.something = A.something+mod` ? – mdurant Aug 15 '22 at 15:31
  • Does this answer your question? [Caching class attributes in Python](https://stackoverflow.com/questions/4037481/caching-class-attributes-in-python) and/or https://stackoverflow.com/questions/15226721/python-class-member-lazy-initialization – mkrieger1 Aug 15 '22 at 15:34

0 Answers0