简体   繁体   中英

How to add items to a class based on user input

I'm in the process of learning python and I am attempting to create a class for a football team. I am just working with different aspects of python to try and get a better understanding. I want a menu based system which will allow the user of the programme to either view all current team members or else register to join the team. Each team member will have a unique ID and when a person joins, it will simple give them the next available number. For example, Chris has the unique ID of 1, Carl has 2, so if Joe joins, he will be automatically given number three. Below is the code I currently have. Viewing card players works perfectly for me but I am struggling with adding a new player.

So my question is, how do I add a new member to the empty list I have which will store all my data and how do I implement that the next person who joins the team will be given the next available number? This is to ensure each member number is unique. Thanks in advance, eager to learn!

class Team(object):

    members = [] #create an empty list to store data

    def __init__(self, user_id, first, last, address):
        self.user_id = user_id
        self.first = first
        self.last = last
        self.address = address
        self.email = first + '.' + last + '@python.com'

        #instance is fully initialized so I am adding it to the list of users
        Team.members.append(self)

    def __str__(self):
        print()
        return 'Membership ID: {}\nFirst Name: {}\nSurname: {}\nLocation: {}\nEmail: {}\n'.format(self.user_id, self.first, self.last, self.address, self.email)
        print()

    @staticmethod
    def all_members():
        for user in Team.members:
            print (user)


    def add_member(Team):
        print()
        print("Welcome to the team!")
        print()
        first_name = input("What's your first name?\n")
        second_name = input("What's your surname?\n")
        address = input("Where do you live?\n")

        for x in Team:
            unique_id = unique_id =+ 1

        user[user_id] = [user_id, first_name, second_name, address]

user_1 = Team(1, 'Chris', 'Parker', 'London')
user_2 = Team(2, 'Carl', 'Lane', 'Chelsea')

def menu(object):

    continue_program = True
    while continue_program:
        print("1. View all members")
        print("2. Add user")
        print("3. Quit")
        try:
            choice = int(input("Please pick one of the above options "))

            if choice == 1:
                Team.all_members()
            elif choice == 2:
                Team.add_member(object)
            elif choice == 3:
                continue_program = False
                print()
                print("Come back soon! ")
                print()
            else:
                print("Invalid choice, please enter a number between 1-3")
                menu(object)
        except ValueError:
            print()
            print("Please try again, enter a number between 1 - 3")
        print()

 #my main program
 menu(object)

You are so close:

@staticmethod
def add_member(): # belongs to the class
    print()
    print("Welcome to the team!")
    print()
    first_name = input("What's your first name?\n")
    second_name = input("What's your surname?\n")
    address = input("Where do you live?\n")

    # get the maximum id and add one
    if Team.members:
        unique_id = max(Team.members, key=lambda m: m.user_id) + 1
    else:
        unique_id = 0
    Team(unique_id , first_name, second_name, address)

And in the main function change on call:

        elif choice == 2:
            Team.add_member()

Things changes:

  • main function operation changed
  • user count field made static and automatically created with addition of new user
  • temp list created to hold users

please comment if you don't understand

all_users = []


class Team(object):
    members = []  # create an empty list to store data
    user_id = 0

    def __init__(self, first, last, address):
        self.user_id = Team.user_id
        self.first = first
        self.last = last
        self.address = address
        self.email = first + '.' + last + '@python.com'
        Team.user_id += 1

        # instance is fully initialized so I am adding it to the list of users
        Team.members.append(self)

    def __str__(self):
        print()
        return 'Membership ID: {}\nFirst Name: {}\nSurname: {}\nLocation: {}\nEmail: {}\n'.format(self.user_id,
                                                                                                  self.first, self.last,
                                                                                                  self.address,
                                                                                                  self.email)
        print()

    @staticmethod
    def all_members():
        for user in all_users:
            print(user)

    @staticmethod
    def add_member():
        print()
        print("Welcome to the team!")
        print()
        first_name = input("What's your first name?\n")
        second_name = input("What's your surname?\n")
        address = input("Where do you live?\n")

        # for x in Team:
        #     unique_id = unique_id = + 1

        all_users.append(Team(first_name, second_name, address))


def main():
    user_1 = Team('Chris', 'Parker', 'London')
    user_2 = Team('Carl', 'Lane', 'Chelsea')

    all_users.extend([user_1, user_2])

    continue_program = True
    while continue_program:
        print("1. View all members")
        print("2. Add user")
        print("3. Quit")
        try:
            choice = int(input("Please pick one of the above options "))

            if choice == 1:
                Team.all_members()
            elif choice == 2:
                Team.add_member()
            elif choice == 3:
                continue_program = False
                print()
                print("Come back soon! ")
                print()
            else:
                print("Invalid choice, please enter a number between 1-3")
                main()
        except ValueError:
            print()
            print("Please try again, enter a number between 1 - 3")
        print()


if __name__ == "__main__":
    main()

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