Getting the class name of an instance in Python

How do I find out a name of class that created an instance of an object in Python if the function I am doing this from is the base class of which the class of the instance has been derived?

Was thinking maybe the inspect module might have helped me out here, but it doesn't seem to give me what I want. And short of parsing the __class__ member, I'm not sure how to get at this information.


Have you tried the __name__ attribute of the class? ie type(x).__name__ will give you the name of the class, which I think is what you want.

>>> import itertools
>>> x = itertools.count(0)
>>> type(x).__name__
'count'

This method works with new-style classes only. Your code might use some old-style classes. The following works for both:

x.__class__.__name__

你想把这个类的名字当作一个字符串吗?

instance.__class__.__name__

type()?

>>> class A(object):
...    def whoami(self):
...       print type(self).__name__
...
>>>
>>> class B(A):
...    pass
...
>>>
>>>
>>> o = B()
>>> o.whoami()
'B'
>>>
链接地址: http://www.djcxy.com/p/1072.html

上一篇: 什么是最佳/常见的RESTful网址动词和动作?

下一篇: 在Python中获取实例的类名