Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

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?

like image 967
edgarbc Avatar asked Aug 31 '18 06:08

edgarbc


People also ask

Can a class attribute be used without an instance of that class?

while you can access class attributes using an instance it's not safe to do so. In python, the instance of a class is referred to by the keyword self. Using this keyword you can access not only all instance attributes but also the class attributes.

What are the attributes of a class?

Class attributes are the variables defined directly in the class that are shared by all objects of the class. Instance attributes are attributes or properties attached to an instance of a class. Instance attributes are defined in the constructor.

What is class object attributes in Python?

A class attribute is a variable that belongs to a certain class, and not a particular object. Every instance of this class shares the same variable. These attributes are usually defined outside the __init__ constructor. An instance/object attribute is a variable that belongs to one (and only one) object.

How do you set a class attribute in Python?

Use dot notation or setattr() function to set the value of class attribute. Python is a dynamic language. Therefore, you can assign a class variable to a class at runtime. Python stores class variables in the __dict__ attribute.


2 Answers

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.

like image 114
Sianur Avatar answered Oct 07 '22 13:10

Sianur


There can be many references to object B(), not only the one in instance of class A. So it's not possible as it is in your code. (Well you could try a hack, like finding all instances of class A in memory and find the one whose attribute b points to your B instance, but that's a really bad idea).

You should explicitly store in instance of B a reference to the owner.

like image 38
warvariuc Avatar answered Oct 07 '22 11:10

warvariuc