Getting the class a variable resides in

Lets say I have something like this -

class A(object):
    c = C()

class B(A):
    pass

class C(object):
    def __init__(self):
        pass

    def get_parent_class(self):
        # This should return B

How would I implement get_parent_class , so that it will work as following -

B.c.get_parent_class() # Returns the class type B (not the instance b!)

Is this even possible?

I basically have a parent class (class A in our example), which contains a variable (var c in the example). I then have a child-class (class B which inherits A )

I want to use functions that C exposes on B , but in order to be used properly, I need C to know it's running on B

(Hope I didn't complicate things in the last explanation...)

Edit - Please note that I'm not trying to get the class of C , that's an easy c.__class__ . I need the class holding c

Thanks!


AFAIK, you cannot do that.

Bc just returns a reference to a C object. Same object can be a member of a list, of an instance of another class (say D) and of another class (say E)

Just add to your example :

class D:
    def __init__(self, c):
        self.c = c
class E:
    c = C()

Then :

>>> c = B.c
>>> E.c = c
>>> d = D(c)
>>> c.a = 1
>>> B.c.a
1
>>> d.c.a
1
>>> E.c.a
1

At that point, c object itself does not know that it belongs to B, d and E. And what should c.get_parent_class() return ? How to decide between B and E ?

You could try to make C aware of its container :

class C(object):
    def __init__(self, clazz):
        self.clazz = clazz

    def get_parent_class(self):
        return self.clazz

class A(object):
    c = C(A)

You would get Acget_parent_class() giving <class '__main__.A'> but as it would be the same object, Bcget_parent_class() will also give <class '__main__.A'> ...


You could take a look at the __bases__ attribute of your object. It returns a tuple of base classes for an object.

You can see it in the docs here.


You can get the class from the name attribute, example:

>>> import itertools
>>> x = itertools.count(0)
>>> x.__class__.__name__
'count'

Or this way:

>>> type(x).__name__
'count'
链接地址: http://www.djcxy.com/p/40956.html

上一篇: RESTful URI设计

下一篇: 获取类变量驻留在