How or can I do the following? Please note that while I declare b_class, I don’t always directly instantiate b_class but is instantiated by a library.
class a_class:
def some_method(self):
"""
get the class instance of b_class in which a_class is instantiated
using that instance, get var1
perform some action based on var1
"""
class b_class:
var1 = "init by the constructor or a method"
a_inst = a_class()
"""
other attributes
"""
You can’t, not without passing a reference to the instance of
b_classwhen you callsome_methodor when you create youra_classinstance.You could store references to that
a_classinstance anywhere, and because of that, you cannot, in Python, know from within the instance method where it has been assigned.So, do this:
Now instances of
a_class‘know’ about their parent, and can reference them via theself.parentinstance variable.