Get subclass name?

后端 未结 4 531
北海茫月
北海茫月 2021-01-03 22: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         


        
相关标签:
4条回答
  • 2021-01-03 22:47
    #!/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.

    0 讨论(0)
  • 2021-01-03 22:50

    SubFoo.__name__

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

    0 讨论(0)
  • 2021-01-03 22:57

    you can use

    SubFoo().__class__.__name__
    

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

    0 讨论(0)
  • 2021-01-03 23:12

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

    class Foo(object):
      ....
    
    0 讨论(0)
提交回复
热议问题