You can't do that.
In Python, variables are just names for values. A value can have many names, for example 60
might be called seconds_per_minute
, minutes_per_hour
, or even speed_limit_mph
, and these names obviously have nothing to do with each other. A value can also have no name at all, for example print(60)
doesn't give 60
any name.
An important point to remember is that when you call a function, your arguments are passed by assignment. That is, the function's parameters become new names for the values that you passed in. So the called function has no idea what name you use for the object you passed, it just knows its own name for that object.
In this case, the object itself doesn't know what class it was created in. You know it, because you know the name of the object (it's B().b
). But the name of the object is not passed to the called function, so getClassOfVariable
has no way of determining which class your A
object was created in.
So, how to work around this limitation? The simplest route is to provide this information to your A
object in its constructor, by passing type(self)
(or self.__class__
, for Python 2.x classic classes) as an argument to A()
and handling it in the A.__init__()
method, like this:
class A():
def __init__(self, owner=None):
self.a = 1
self.owner = owner
class B():
def __init__(self):
self.b = A(type(self))
You can then inspect the B().b.owner
attribute to find out which class created your A
object. However, if you create a subclass of B
, then type(self)
will be that subclass and not B
. If you still need to get B
in that case, then you should pass B
instead of type(self)
.