Is it possible to refer to the owner class that an object belongs to as an attribute?

  • A+
Category:Languages

I am not quite sure this is possible (or something similar) in python. I want to access a method (or another object) of a class from an object that is an attribute of such class.

Consider the following code:

class A():   def __init__(self):      self.b = B()      self.c = C()   def print_owner(self):      print('owner')  class B():   def __init__(self):      pass   def call_owner(self):      self.owner().print_owner() 

so that b as an object attribute of class A, can refer to a method or attribute of A?

Or similarly, is it possible that b can access c?

 


It's possible. You can pass a reference to A to B constructor:

...     self.b = B(self) ...  class B:     def __init__(self, a):         self.a = a 

So, B.a stores the reference to its owner A.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: