0

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!

thomas
  • 1,133
  • 1
  • 12
  • 31
  • `c = C()` raises an exception because `C` is not defined yet. – falsetru Jul 31 '15 at 09:14
  • possible duplicate of [Getting the class name of an instance in Python](http://stackoverflow.com/questions/510972/getting-the-class-name-of-an-instance-in-python) – Stiffo Jul 31 '15 at 09:21
  • 1
    @Stiffo : not a duplicate OP wants the class name of a class *containing* c, not the class name of C nor any of its parent. – Serge Ballesta Jul 31 '15 at 09:36

3 Answers3

1

AFAIK, you cannot do that.

B.c 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 A.c.get_parent_class() giving <class '__main__.A'> but as it would be the same object, B.c.get_parent_class() will also give<class '__main__.A'> ...

Serge Ballesta
  • 143,923
  • 11
  • 122
  • 252
-1

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.

Eric Bulloch
  • 827
  • 6
  • 10
-1

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'
Stiffo
  • 818
  • 6
  • 19