0

I am trying to print ages of all instances of my player class. In my mind, it was something like that "Bob is an instance of "player" class, Bob has a name which is obviously Bob and an age". I also tried to make a variable with a name provided by the user.

names=[]
class player:
    def __init__(self,name,age):
        self.name=name
        self.age=age


playerNumber=int(input("How many players? "))
while playerNumber:
    name=input("enter your name ")
    age=input("enter your age ")
    vars()['name']=player(name,age)
    names.append(vars()['name'].name)
    playerNumber-=1
for x in names:
    print(vars()["x"].age)
leana radu
  • 11
  • 2
  • 2
    What's with the `vars()["x"].age` weirdness? Who taught you that? Why not just `x.age`? – Peter Wood Jan 16 '19 at 18:06
  • 1
    In what way isn't your code working? What did you expect? What did it actually do? What don't you understand? Create an example with just the part you don't understand rather than a lot of code. See how to create a [mcve]. Welcome to Stack Overflow. – Peter Wood Jan 16 '19 at 18:07
  • Why are you doing this: `vars()['name']=player(name,age)`? Why not `name = player(name, age)`, or better yet, use `player` the local variable for a `Player` object, and use the standard style of UpperCase class names, – juanpa.arrivillaga Jan 16 '19 at 18:08
  • as I understand in my case x is a string and i needed a variable named after x – leana radu Jan 16 '19 at 18:08
  • You could keep a list of `players` rather than `names`. Or perhaps a dictionary mapping the name to the player. – Peter Wood Jan 16 '19 at 18:09
  • @leanaradu no, you don't. Don't use dynamic variable names. Use a `dict` if you want to map strings to another kind of object. In any case, what you would want to do then is `vars()[x]` not `vars['x']`, but *don't do that*. Note, you are simply just using a dict here anyway, but the dict is the global namespace, which you really shouldn't abuse this way. It's an issue of code organization. – juanpa.arrivillaga Jan 16 '19 at 18:09
  • 1
    @PeterWood thank you, i got it – leana radu Jan 16 '19 at 18:12
  • Check out the answers to the questions here: https://stackoverflow.com/questions/1373164/how-do-i-create-a-variable-number-of-variables note, some answers show you how to dynamically create variables, but pay attention to the highly voted answers that show you a better way – juanpa.arrivillaga Jan 16 '19 at 18:14
  • Possible duplicate of [How do I create a variable number of variables?](https://stackoverflow.com/questions/1373164/how-do-i-create-a-variable-number-of-variables) – manveti Jan 16 '19 at 18:39

0 Answers0