[英]How to print name of class in Python
我正在尝试找到语法来打印我的班级名称。 给定以下内容:
#!/usr/bin/python
class a:
whatever = 0
foo = a()
bar = a()
listOfClasses = [foo,bar]
for l in listOfClasses:
print l
#I'm trying to find the syntax to print the name of the class (eg foo and bar)
从您的示例中,您正在寻找实例的名称( foo
和bar
)。 简而言之,由于存在多个指向同一实例的命名变量,因此无法实现。
如果要查找类的名称(即a
),则可以使用l.__class__.__name__
。 但是,这也不是完全防弹的:
In [10]: class A(object): pass
....:
In [11]: A().__class__.__name__
Out[11]: 'A'
In [12]: Z = A
In [13]: Z().__class__.__name__
Out[13]: 'A'
无法获得此信息,因为在Python对象中没有这样的名称(只有对对象的引用才具有名称)。 考虑:
foo = a()
bar = foo # bar is now another name for foo
lst = [foo, bar] # both elements refer to the *same* object
在这种情况下,假设的“名称”函数将为lst
每个元素打印什么? 为了表明两个元素都引用同一个对象:
print [id(x) for x in lst]
将打印相同的id
两次。
您可以使用此instance.__class__.__name__
: instance.__class__.__name__
所以在您的情况下: a = foo.__class__.__name__
或b = bar.__class__.__name__
a
和b
是字符串类型。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.