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
?
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.
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With