我是一名学生开发人员,正在为即将到来的测试学习。我一直在做一个关于继承和多态性的练习题,并设法达到预期的结果,但我似乎不理解我自己的代码后,试图彻底分析它。我想创建一个超类'播放器',并初始化超类中的对象,以创建篮球运动员并将他们组成一个团队,然后使用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'”。
2条答案
按热度按时间dnph8jn41#
这是由于您对
__init__
方法的定义:字符串
在该定义中,您的代码声明,为了创建新的
Player
对象,必须传递player_name
。因此,如果您尝试在不提供该数据的情况下初始化
Player
,则会失败。至于为什么从
BasketballPlayer
的__init__
方法中删除它会失败,你会注意到该方法调用了super().__init__(player_name)
。如果从BasketballPlayer
中删除需求,而不是从Player
中删除,那么__init__
调用将失败,因为初始化一个对象需要调用它继承的所有类的__init__
函数。s4n0splo2#
我觉得这样更好:
字符串