对象初始化期间的参数传递(Python OOP)

snz8szmq  于 2023-11-20  发布在  Python
关注(0)|答案(2)|浏览(97)

我是一名学生开发人员,正在为即将到来的测试学习。我一直在做一个关于继承和多态性的练习题,并设法达到预期的结果,但我似乎不理解我自己的代码后,试图彻底分析它。我想创建一个超类'播放器',并初始化超类中的对象,以创建篮球运动员并将他们组成一个团队,然后使用str显示团队成员。方法。下面是www.example.com的代码Player.py:

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

    def get_player_name(self):
        return self.player_name

    def set_player_name(self, player_name):
        self.player_name = player_name

class BasketballPlayer(Player):

    positions = ['Guard', 'Forward', 'Center']

    def __init__(self, player_name):
        super().__init__(player_name)
        self.player_position = None

    def get_player_position(self):
        return self.player_position

    def set_player_position(self, player_position):
        self.player_position = player_position
        if self.player_position not in BasketballPlayer.positions:
            print("Invalid position for basketball player.")
            self.player_position = ""

    def __str__(self):
        return f"{self.get_player_name()} playing as a {self.player_position}"

字符串
下面是我的测试程序的代码,我在其中执行我的函数:

from Player import *                                                                              
                                                                                                  
                                                                                                  
List_of_players = []                                                                              
team_name = str(input("Please enter the basketball team name: "))                                 
                                                                                                  
for i in range(5):                                                                                
    player_name = str(input("Please enter player name: "))                                        
    player_position = str(input("Please enter the basketball player's position: "))               
                                                                                                  
    BasketBallPlayer_obj = BasketballPlayer(player_name)                                          
                                                                                                  
    BasketBallPlayer_obj.set_player_position(player_position)                                     
    BasketBallPlayer_obj.set_player_name(player_name)                                             
                                                                                                  
    List_of_players.append(BasketBallPlayer_obj)                                                  
                                                                                                  
print(f"Team {team_name} consists of the following players: ")                                    
for i in range(len(List_of_players)):                                                             
    print(List_of_players[i])


我正在使用for循环为5个球员创建一个篮球运动员对象5次。有人能帮我解释一下为什么在BasketBallPlayer_obj = BasketballPlayer(player_name)中初始化BasketBallPlayer_obj时需要传入'player_name'参数吗?如果我删除参数传递,并且不知道为什么需要传入'player_name'参数,我会得到一个TypeError,谢谢你这么多提前回答这个问题!
我尝试在初始化对象时删除'player_name'参数,但它抛出了一个TypeError,说“Player.init()missing 1 required positional argument:'player_name'”。

dnph8jn4

dnph8jn41#

这是由于您对__init__方法的定义:

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

字符串
在该定义中,您的代码声明,为了创建新的Player对象,必须传递player_name
因此,如果您尝试在不提供该数据的情况下初始化Player,则会失败。
至于为什么从BasketballPlayer__init__方法中删除它会失败,你会注意到该方法调用了super().__init__(player_name)。如果从BasketballPlayer中删除需求,而不是从Player中删除,那么__init__调用将失败,因为初始化一个对象需要调用它继承的所有类的__init__函数。

s4n0splo

s4n0splo2#

我觉得这样更好:

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

    @property
    def player_name(self):
        return self._player_name

    @player_name.setter
    def player_name(self, val):
        self._player_name = val

positions = ['Guard', 'Forward', 'Center']

class BasketballPlayer(Player):

    def __init__(self, player_position, player_name):
        super().__init__(player_name)
        self.player_position = player_position

    @property
    def player_position(self):
        return self._player_position

    @player_position.setter
    def player_position(self, value):
        if value in positions:
            self._player_position = value
        else:
            print("Invalid position for basketball player.")

    def __str__(self):
        return f"{self.player_name} playing as {self.player_position}"

List_of_players = []
team_name = str(input("Please enter the basketball team name: "))

for i in range(5):
    name = str(input("Please enter player name: "))
    playerposition = str(input("Please enter the basketball player's position: "))
    BasketBallPlayer_obj = BasketballPlayer(player_name=name, player_position=playerposition)
    List_of_players.append(BasketBallPlayer_obj)

print(f"Team {team_name} consists of the following players: ")
for i in range(len(List_of_players)):
    print(List_of_players[i])

字符串

相关问题