Is it possible to refer to the owner class that an object belongs to as an attribute?
Is it possible to refer to the owner class that an object belongs to as an attribute?
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
?
b
A
A
Or similarly, is it possible that b
can access c
?
b
c
self.owner
self.owner()
Consider modifying the
WeakAttribute
example code from PEP 487. (If you're not using python 3.6, it's still possible with metaclasses.)– o11c
Aug 31 at 7:05
WeakAttribute
3 Answers
3
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.
self.owner
instead of self.a
according to OP, but the concept is 100% sound.– Mad Physicist
Aug 31 at 6:33
self.owner
self.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).
B()
A
A
b
You should explicitly store in instance of B
a reference to the owner.
B
You have a couple of options here. The better one is probably @Sianur suggests. It's simple, effective, and explicit. Give that answer an upvote.
Another option is to have the owner force itself on its minions. B
can do something like
B
def call_owner(self):
if hasattr(self, 'owner'):
self.owner().print_owner()
else:
print('I am free!')
Meanwhile, A
would set the owner attribute to itself:
A
def __init__(self):
self.b = B()
self.c = C()
self.b.owner = self.c.owner = self
In any case, if you want an object to have access to another object, store the reference into an accessible place. There's no magic here.
Thanks for contributing an answer to Stack Overflow!
But avoid …
To learn more, see our tips on writing great answers.
Some of your past answers have not been well-received, and you're in danger of being blocked from answering.
Please pay close attention to the following guidance:
But avoid …
To learn more, see our tips on writing great answers.
Required, but never shown
Required, but never shown
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
self.owner
makes much more sense thanself.owner()
here.– Mad Physicist
Aug 31 at 6:32