23

Is it possible to get the name of a subclass? For example:

class Foo:
    def bar(self):
        print type(self)

class SubFoo(Foo):
    pass

SubFoo().bar()

will print: < type 'instance' >

I'm looking for a way to get "SubFoo".

I know you can do isinstance, but I don't know the name of the class a priori, so that doesn't work for me.

martineau
  • 119,623
  • 25
  • 170
  • 301
Bryan Ward
  • 6,443
  • 8
  • 37
  • 48

5 Answers5

16

you can use

SubFoo().__class__.__name__

which might be off-topic, since it gives you a class name :)

mykhal
  • 19,175
  • 11
  • 72
  • 80
13
#!/usr/bin/python
class Foo(object):
  def bar(self):
    print type(self)

class SubFoo(Foo):
  pass

SubFoo().bar()

Subclassing from object gives you new-style classes (which are not so new any more - python 2.2!) Anytime you want to work with the self attribute a lot you will get a lot more for your buck if you subclass from object. Python's docs ... new style classes. Historically Python left the old-style way Foo() for backward compatibility. But, this was a long time ago. There is not much reason anymore not to subclass from object.

nate c
  • 8,802
  • 2
  • 27
  • 28
5

SubFoo.__name__

And parents: [cls.__name__ for cls in SubFoo.__bases__]

Jason Scheirer
  • 1,668
  • 16
  • 14
3

It works a lot better when you use new-style classes.

class Foo(object):
  ....
Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
1

Just a reminder that this issue doesn't exist in Python 3.x and print(type(self)) will give the more informative <class '__main__.SubFoo'> instead of bad old < type 'instance' >.

This is because object is subclassed automatically in Python 3.x, making every class a new-style class.

More discussion at What is the purpose of subclassing the class "object" in Python?.

Like others pointed out, to just get the subclass name do print(type(self).__name__).

Harsh Verma
  • 529
  • 6
  • 10