如何查找用于在Python中创建对象实例的类的名称?

我不确定应该使用inspect模块还是解析__class__属性。


当前回答

问得好。

下面是一个基于GHZ的简单示例,可能会对某人有所帮助:

>>> class person(object):
        def init(self,name):
            self.name=name
        def info(self)
            print "My name is {0}, I am a {1}".format(self.name,self.__class__.__name__)
>>> bob = person(name='Robert')
>>> bob.info()
My name is Robert, I am a person

其他回答

要获取实例类名:

type(instance).__name__

or

instance.__class__.__name__

两者都一样

是否要将类的名称作为字符串?

instance.__class__.__name__

类型()?

>>> class A:
...     def whoami(self):
...         print(type(self).__name__)
...
>>>
>>> class B(A):
...     pass
...
>>>
>>>
>>> o = B()
>>> o.whoami()
'B'
>>>

你尝试过类的__name__属性吗?即类型(x)__name__会给你班级的名字,我想这就是你想要的。

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

如果您仍在使用Python 2,请注意上述方法仅适用于新型类(在Python 3+中,所有类都是“新型”类)。您的代码可能使用一些旧式类。以下两项都适用:

x.__class__.__name__

您可以首先使用type,然后使用str从中提取类名。

class foo:pass;

bar:foo=foo();
print(str(type(bar))[8:-2][len(str(type(bar).__module__))+1:]);

后果

foo