0

I'm trying to make a class, Player, and I'd like the user to create objects, say to add to their team.

Every tutorial will have something like this to create new players, say Jordan.

class Player:
    def __init__(self, name):
        self.name = name

p1 = Player('Jordan')
p2 = Player('Kobe')

But I want the user to have the ability to create new players, and they're not going to code, right? And I would rather the object variable be just the player name, like, "Jordan", or "Kobe".

So if everything was manual, I could say,

jordan = Player('Jordan')
kobe = Player('Kobe')

So to come up with a function to have users create players, what should it look like? And what would the variable be? Any way to get it assigned as the player name? Or at least a serialized number like p1, p2, p3, ...?

def create_player():
    new_player = input("Which player would you like to create? ")
    name_of_variable_for_player = Player(new_player)

Ok, so follow on question.

What happens when you just have a static variable in the create function?


def create_player():
    p = Player(input("What player would you like to make? ")

StuNami
  • 1
  • 2
  • You can refer to: https://stackoverflow.com/questions/29824194/setting-user-input-to-variable-name – CodeCop May 23 '20 at 00:17
  • Does this answer your question? [How do I create a variable number of variables?](https://stackoverflow.com/questions/1373164/how-do-i-create-a-variable-number-of-variables) e.g. `roster = {}; name = 'Jordan'; roster[name] = Player(name)` – wjandrea May 23 '20 at 01:35
  • wjandrea, I'm not sure what you're suggesting? Does all that go on one line? or sequentially down a line at every ";"? – StuNami May 23 '20 at 04:27
  • @StuNami OK, I'll write you an answer – wjandrea May 23 '20 at 17:49
  • I'm not sure what you're trying to do with the "static variable in the create function" since `p` is lost as soon as the function ends. – wjandrea May 23 '20 at 18:03

1 Answers1

0

Use a dict instead of dynamic variables. For more details see How do I create a variable number of variables?

In this case that might look something like this:

class Player:
    def __init__(self, name):
        self.name = name

    def __repr__(self):  # Adding this for better output
        cls_name = type(self).__name__
        return '{}({!r})'.format(cls_name, self.name)

my_team = {}
name = input("Which player would you like to create? ")
my_team[name] = Player(name)
print(my_team)

Example run:

Which player would you like to create? Shaq
{'Shaq': Player('Shaq')}

How to turn that into a function might vary based on what you're trying to do, but you could start here:

def add_player_to_roster(roster):
    name = input("Which player would you like to create? ")
    roster[name] = Player(name)

my_team = {}
add_player_to_roster(my_team)
print(my_team)
wjandrea
  • 28,235
  • 9
  • 60
  • 81