简体   繁体   中英

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 ). 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__ . 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). 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 ? To show that both elements refer to the same object:

print [id(x) for x in lst]

will print the same id twice.

You can use this: instance.__class__.__name__

so in your case: a = foo.__class__.__name__

or b = bar.__class__.__name__

a and b are of type string.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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