1

Is there a way to get a value from class A assigned at runtime from class B without passing it as as argument to the constructor? (e.g. not using new_b = B(self.value))

class_a.py

from class_b import B

class A():
    def __init__(self, value):
        self.value = value
        self.load()

    def load(self):
        new_b = B()

class_b.py

class B():
    def __init__(self):
        self.value = A.value # here we should get a value from instantiating class A
techkuz
  • 3,608
  • 5
  • 34
  • 62

2 Answers2

1

Yes, this is possible, but never ever do that. This is bad practice and if you start thinking about doing something like that, you are doing it wrong. Anyway, this line would do it:

import inspect

inspect.getouterframes(inspect.currentframe())[1].frame.f_locals["self"].value
MegaIng
  • 7,361
  • 1
  • 22
  • 35
-1

As mentioned, the more explicit way would be to pass the argument. But, you can try using Super keyword to initialize Base Class methods from where you want to fetch the values.

Refer to this post for your reference,Understanding Python super() with __init__() methods

NightOwl19
  • 419
  • 5
  • 24