How do I print the name of an instance in Python?

Asked

Viewed 81 times

2

class Panzer():
   def __init__(self):
      self.life = 100
      self.blin = 100

drogo = Panzer()
cabal = Panzer()
sirius = Panzer()

group = [drogo, cabal, sirius]
for i in group:
print()

What should I put on print() to get the exit:

drogo
cabal
sirius
  • Did any of the answers solve your question? Do you think you can accept one of them? Check out the [tour] how to do this, if you haven’t already. You would help the community by identifying what was the best solution for you. You can accept only one of them. But you can vote on any question or answer you find useful on the entire site.

1 answer

5

Don’t do it and don’t do it.

You want to print the variable name, and that you know to a certain extent what it is. What would be the advantage of printing the name of something that’s already in the code? What good would it do for the user to know the name of the variable that object is there? It makes no sense to your code and makes no sense to the user. Maybe you’re missing What is a variable? and In programming, what is an object?. May also be useful: Instances and variables in C#

When the object is used somewhere other than a variable named as it was in the list, there is obviously no way to print something that does not exist.

I’ll write a code that has exactly the same result (in fact the variables are completely redundant and unnecessary), tells me where is the name:

group = [Panzer(), Panzer(), Panzer()]

Instances (objects) have no names. You can print internal features of them, it depends on each object. If you need to have a name in it you need to define the object to have a name. Maybe you want something like this:

class Panzer():
   def __init__(self, name):
      self.name = name
      self.life = 100
      self.blin = 100

group = [Panzer("drogo"), Panzer("cabal"), Panzer("sirius")]
for i in group:
    print(i.name)

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

  • Did the answer solve your question? Do you think you can accept it? See [tour] if you don’t know how you do it. This would help a lot to indicate that the solution was useful to you. You can also vote on any question or answer you find useful on the entire site

Browser other questions tagged

You are not signed in. Login or sign up in order to post.