1

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)
3
  • That's not the name of your class, that's the name of your variables that hold instances of a class. The class name is "a". The best you'll get is to look at the locals() dictionary and find values that are instances of the class you want. Commented Dec 3, 2011 at 21:00
  • The name of the class in both cases is a. You're trying to find the name of the variable originally assigned, and it's simply not possible. Commented Dec 3, 2011 at 21:00
  • @vanza: It's a fine point, but "variables" in Python don't hold instances. Variables are names bound to objects that exist somewhere else. Commented Dec 3, 2011 at 21:03

3 Answers 3

3

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 (i.e. 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'
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

1

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.