简体   繁体   English

获取子类名称?

[英]Get subclass name?

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' >将打印: < type 'instance' >

I'm looking for a way to get "SubFoo" .我正在寻找一种获取"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.我知道你可以做isinstance ,但我不知道 class 先验的名字,所以这对我不起作用。

you can use 您可以使用

SubFoo().__class__.__name__

which might be off-topic, since it gives you a class name :) 这可能是偏离主题的,因为它给你一个类名:)

#!/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. object子类化为你提供了新式的类(不再那么新了 - python 2.2!)无论何时你想要使用self属性,如果从对象继承,你将获得更多的帮助。 Python's docs ... new style classes . Python的文档...... 新的样式类 Historically Python left the old-style way Foo() for backward compatibility. 从历史上看,Python为了向后兼容而离开旧式方式Foo() But, this was a long time ago. 但是,这是很久以前的事了。 There is not much reason anymore not to subclass from object. 没有太多理由不从对象继承。

It works a lot better when you use new-style classes. 使用新式类时,它的效果会更好。

class Foo(object):
  ....

SubFoo.__name__

和父母: [cls.__name__ for cls in SubFoo.__bases__]

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' > .提醒一下,这个问题在Python 3.x中不存在print(type(self))将提供更多信息<class '__main__.SubFoo'>而不是旧的< type 'instance' >

This is because object is subclassed automatically in Python 3.x , making every class a new-style class.这是因为objectPython 3.x中被自动子类化,使每个 class 成为new-style class。

More discussion at What is the purpose of subclassing the class "object" in Python?更多讨论在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__) .就像其他人指出的那样,只需获取子类名称即可print(type(self).__name__)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM