简体   繁体   English

如何在Python中打印类的名称

[英]How to print name of class in Python

I am trying to find the syntax to print the name of my classes. 我正在尝试找到语法来打印我的班级名称。 Given the following: 给定以下内容:

#!/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)

From your example, you're looking for the name of the instance ( foo and bar ). 从您的示例中,您正在寻找实例的名称( foobar )。 In a nutshell, there isn't a way to do it since there could be multiple named variables pointing to the same instance. 简而言之,由于存在多个指向同一实例的命名变量,因此无法实现。

If you're looking for the name of the class (ie a ), you could use l.__class__.__name__ . 如果要查找的名称(即a ),则可以使用l.__class__.__name__ However, this is not totally bullet-proof either: 但是,这也不是完全防弹的:

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'

It's not possible to get this information, because in Python objects do not have names as such (only references to objects have names). 无法获得此信息,因为在Python对象中没有这样的名称(只有对对象的引用才具有名称)。 Consider: 考虑:

foo = a()
bar = foo # bar is now another name for foo

lst = [foo, bar] # both elements refer to the *same* object

In this case, what would your hypothetical "name" function print for each element of lst ? 在这种情况下,假设的“名称”函数将为lst每个元素打印什么? To show that both elements refer to the same object: 为了表明两个元素都引用同一个对象:

print [id(x) for x in lst]

will print the same id twice. 将打印相同的id两次。

You can use this: instance.__class__.__name__ 您可以使用此instance.__class__.__name__instance.__class__.__name__

so in your case: a = foo.__class__.__name__ 所以在您的情况下: a = foo.__class__.__name__

or b = bar.__class__.__name__ b = bar.__class__.__name__

a and b are of type string. ab是字符串类型。

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

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