Write a class for Team which should have function to prints players details

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP





.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty margin-bottom:0;







up vote
1
down vote

favorite












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()






share|improve this question



























    up vote
    1
    down vote

    favorite












    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()






    share|improve this question























      up vote
      1
      down vote

      favorite









      up vote
      1
      down vote

      favorite











      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()






      share|improve this question













      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()








      share|improve this question












      share|improve this question




      share|improve this question








      edited Jul 13 at 10:45









      Mathias Ettinger

      21.7k32875




      21.7k32875









      asked Jul 13 at 10:22









      Mrityunjay

      84




      84




















          1 Answer
          1






          active

          oldest

          votes

















          up vote
          1
          down vote



          accepted










          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.






          share|improve this answer























            Your Answer




            StackExchange.ifUsing("editor", function ()
            return StackExchange.using("mathjaxEditing", function ()
            StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix)
            StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
            );
            );
            , "mathjax-editing");

            StackExchange.ifUsing("editor", function ()
            StackExchange.using("externalEditor", function ()
            StackExchange.using("snippets", function ()
            StackExchange.snippets.init();
            );
            );
            , "code-snippets");

            StackExchange.ready(function()
            var channelOptions =
            tags: "".split(" "),
            id: "196"
            ;
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function()
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled)
            StackExchange.using("snippets", function()
            createEditor();
            );

            else
            createEditor();

            );

            function createEditor()
            StackExchange.prepareEditor(
            heartbeatType: 'answer',
            convertImagesToLinks: false,
            noModals: false,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: null,
            bindNavPrevention: true,
            postfix: "",
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            );



            );








             

            draft saved


            draft discarded


















            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f198416%2fwrite-a-class-for-team-which-should-have-function-to-prints-players-details%23new-answer', 'question_page');

            );

            Post as a guest






























            1 Answer
            1






            active

            oldest

            votes








            1 Answer
            1






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes








            up vote
            1
            down vote



            accepted










            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.






            share|improve this answer



























              up vote
              1
              down vote



              accepted










              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.






              share|improve this answer

























                up vote
                1
                down vote



                accepted







                up vote
                1
                down vote



                accepted






                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.






                share|improve this answer















                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.







                share|improve this answer















                share|improve this answer



                share|improve this answer








                edited Jul 13 at 12:10


























                answered Jul 13 at 10:49









                Graipher

                20.4k42981




                20.4k42981






















                     

                    draft saved


                    draft discarded


























                     


                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function ()
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f198416%2fwrite-a-class-for-team-which-should-have-function-to-prints-players-details%23new-answer', 'question_page');

                    );

                    Post as a guest













































































                    Popular posts from this blog

                    Chat program with C++ and SFML

                    Function to Return a JSON Like Objects Using VBA Collections and Arrays

                    Will my employers contract hold up in court?