班级运动员创建一个具有属性的对象;名称,总分,平均值,偏差,机会 我将对象重命名为播放器。当我读取行时,我希望我的类中的属性发生变化,以便它与文件中给出的信息相匹配。我已经阅读了一些关于超类的内容,但我不知道如何合并,在这种情况下使用是不正确的方法。我希望创建的播放器对象看起来像这样:
player.Name = Donald Duck
player.TotalScore=0
player.Average = 18
player.Deviation = 2
player.Chance = 0.16
class Athlete():
def __init_(self):
self.Name=name
self.TotalScore=0
self.Average=0
self.Deviation=0
self.Chance=0.0
def PlayersFromFile(NameOfInputfile):
#define a list for player objects
PlayerList =[]
file = open(NameOfInputfile,'r')
lines = file.readlines()
for line in lines:
var1, var2, var3,var4 = line.split("\t")
var4 = float(var4.rstrip())
player = Athlete
player.Name = var1
player.Average = float(var2)
player.Deviation = float(var3)
player.Chance =var4
playerList.append(player)
这个文件的样子如下:
Donald Duck 18 3 0.16
The Bear 17 4 0.25
Fair Brow 16 5 0.48
答案 0 :(得分:1)
对文件进行少量更改可能有效
class Athlete():
def __init_(self, name=None):
self.Name=name
self.TotalScore=0
self.Average=0
self.Deviation=0
self.Chance=0.0
def PlayersFromFile(NameOfInputfile):
#define a list for player objects
PlayerList =[]
file = open(NameOfInputfile,'r')
lines = file.readlines()
for line in lines:
var1, var2, var3,var4 = line.split("\t")
var4 = float(var4.rstrip())
player = Athlete()
player.Name = var1
player.Average = float(var2)
player.Deviation = float(var3)
player.Chance =var4
playerList.append(player)
注意__init__
函数中Athlete类中的name参数,以及创建播放器实例时Athlete调用中的双括号。
答案 1 :(得分:0)
无论属于self.Chancen
的属性是什么,都不在文件中,您将拥有默认值:
class Athlete():
def __init__(self,name, total_score=0, avg=0, dev=0, chnce=0.0):
self.name = name
self.total_score = total_score
self.average = avg
self.deviation = dev
self.chance = chnce
def players_from_file(input_file):
player_list =[]
with open(input_file) as f:
for line in f:
name, score, avg, dev = line.split("\t")
dev = float(dev.rstrip())
player_list.append(Athlete(name,float(score),float(avg), dev))
return player_list
player = players_from_file("in.csv")
[<__main__.Athlete instance at 0x7f26194c5b00>, <__main__.Athlete instance at 0x7f26194c5ab8>, <__main__.Athlete instance at 0x7f26194c5bd8>]
for player in players:
print(player.name,player.total_score)
('Donald Duck', 18.0)
('The Bear', 17.0)
('Fair Brow', 16.0)
答案 2 :(得分:0)
您正在PlayersFromFile方法中定义PlayerList,这意味着一旦该方法完成,它将无法访问/删除。
播放器是您在另一个运动员实例中工作的运动员的实例,这很麻烦。并为玩家提供了许多方法来创建它不需要的新实例。
制作一个具有玩家需要属性的类,然后为每个玩家创建一个新实例。
我恐怕不能再回答这个问题了,建议你在基础层面上阅读命名空间和课程。
编辑:错过了运动员课程的错误实例,答案得到纠正。