tags:

views:

58

answers:

4

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.

+2  A: 

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

class Foo(object):
  ....
Ignacio Vazquez-Abrams
+1  A: 

you can use

SubFoo().__class__.__name__

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

mykhal
@ars not exactly
mykhal
Whoops, sorry. You're right, my bad.
ars
+2  A: 
#!/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
And `Foo()` won't work on old-enough versions of Python either.
Ignacio Vazquez-Abrams
A: 

SubFoo.__name__

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

Jason Scheirer