1
\$\begingroup\$

I have written it using aggregation but i feel its not the best way we can do this. Please suggest is there any other way to do this. I think we can also built this without using player class, just store players details in nested list or dict. Please suggest what is the best way.

class Player(object):
    def __init__(self, name, age, skills, style=None):
        self.name = name
        self.age = age
        self.skills = skills
        self.style = style

    def get_player(self):
        print(self.name,self.age,self.skills,self.style)


class Team(object):
    def __init__(self, name):
        self.name = name
        self._players = []

    def add_player(self, obj):
        if isinstance(obj, Player):
            self._players.append(obj)
        else:
            print("Please provide player object")

    def get_players(self):
        for player in self._players:
            player.get_player()


if __name__ == "__main__":

    p1 = Player("Mahendra", 46, "Wicket Kipper", "Right-Hand Batsman")
    p2 = Player("Sachin", 35, "Batsman", "Right-Hand Batsman")
    p3 = Player("Saurabh", 44, "Batsman", "Left-Hand Batsman")
    p4 = Player("Zahir", 38, "Bauwller", "Medium Pace Bauwller")
    p5 = Player("Yuvraj", 43, "All rounder")

    t = Team("India")
    t.add_player(p1)
    t.add_player(p2)
    t.add_player(p3)
    t.add_player(p4)
    t.add_player(p5)

    t.get_players()
\$\endgroup\$
  • \$\begingroup\$ Could you please give me an explanation on how this code works? \$\endgroup\$ – Mehdi Abbassi Mar 18 at 12:39
1
\$\begingroup\$

You should learn about Python's magic (or dunder) methods. They allow your custom class to interact with the built-in functions (by e.g. defining what a + b means for objects of your class, or, which is relevant here, what print(team) or print(player) mean.

For this I would add two methods, first the __iter__ method, which allows you to iterate over your team and get each player, and the __str__ method, which defines how your class prints:

class Player:
    def __init__(self, name, age, skills, style=None):
        self.name = name
        self.age = age
        self.skills = skills
        self.style = style

    def __str__(self):
        return f"{self.name} {self.age} {self.skills} {self.style or ''}"


class Team:
    def __init__(self, name, players=None):
        self.name = name
        if players is not None:
            self._players = list(players)
        else:
            self._players = []

    def add_player(self, obj):
        if isinstance(obj, Player):
            self._players.append(obj)
        else:
            print("Please provide player object")

    def __iter__(self):
        return iter(self._players)

    def __str__(self):
        out = [f"Team name: {self.name}", "Players:"]
        out.extend(str(player) for player in self)
        return "\n".join(out)


if __name__ == "__main__":

    players = [Player("Mahendra", 46, "Wicket Kipper", "Right-Hand Batsman"),
               Player("Sachin", 35, "Batsman", "Right-Hand Batsman"),
               Player("Saurabh", 44, "Batsman", "Left-Hand Batsman"),
               Player("Zahir", 38, "Bauwller", "Medium Pace Bauwller"),
               Player("Yuvraj", 43, "All rounder")]

    india = Team("India", players)
    print(india)

    # equivalent:
    print("Team name:", india.name)
    print("Players:")
    for player in india:
        print(player)

I also added an optional keyword argument to the Team constructor to allow passing in a list of players right away.

I also removed the explicit inheritance from object, which is not needed anymore in Python 3 (only for backwards compatibility with Python 2), as all classes are new-style classes.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.