晚上好,我的代码遇到了一些麻烦。我的目标是将数据输入到类中。所以我有p1 = Pitch(“ CH”,“ S”)。从这里开始,我要运行一个函数,该函数打印带有输入该数据的语句的语句,并使用另一个函数在print语句中查找平均速度。我的不好是,如果这在很大程度上没有意义,请允许我发布到目前为止的代码,看看它是否可以提供更好的视觉效果。
import csv
fh = open('pitches.csv')
spreadsheet = csv.DictReader(fh)
startspeed = []
class Pitch:
def __init__(self, name, result):
fh = open('pitches.csv')
self.spreadsheet = csv.DictReader(fh)
self.name = name
self.result = result
def avg_start_speed(self):
for row in spreadsheet:
if row['pitch_type'] == str(self.name) and row['type'] == str(self.result):
startspeed.append(row['start_speed'])
return sum(startspeed) / len(startspeed)
def myfunc(self):
for row in spreadsheet:
if row['pitch_type'] == self.name:
print("The average speed of a " + self.result + " for a "
+ self.name + " is " + str(self.avg_start_speed()))
p1 = Pitch("CH", "S")
p1.myfunc()
我收到此错误
NameError:未定义名称'avg_start_speed'
我不确定该如何解决。感谢您提前提出所有建议。
CSV示例:
start_speed end_speed type pitch_type
92.9 84.1 S FF
92.8 84.1 S FF
94.1 85.2 S FF
91 84 B FF
75.4 69.6 B CU
92.9 84.8 S CH
93.3 85.3 B FF
89.3 82.4 X FC
92.1 85 S CH
答案 0 :(得分:1)
您的代码中存在一些问题。
假设您想将其用作类方法,则self
中缺少一个def avg_start_speed():
参数。 (我也看到您在函数定义中也使用self
)。
因此它将是def avg_start_speed(self):
您还希望像avg_start_speed()
一样使用self
中的myfunc
调用函数self.avg_start_speed()
您还可以在类外定义spreadsheet
。为什么不在类内定义它,也许在__init__
中定义它并使用它呢?
您也没有在startspeed
函数中声明avg_start_speed()
变量
永远记住,对于类方法,第一个参数始终为self
,您可以使用class.func()
在类中的其他类方法中调用它们
生效后,代码将如下所示
import csv
class Pitch:
def __init__(self, name, result, spreadsheet):
self.spreadsheet = spreadsheet
self.name = name
self.result = result
def avg_start_speed(self):
#Calculate average speed and return
startspeed = []
for row in self.spreadsheet:
if row['pitch_type'] == self.name and row['type'] == self.result:
startspeed.append(float(row['start_speed']))
return sum(startspeed) / len(startspeed)
def myfunc(self):
#Call avg_start_speed here and print it using string.format
avg_start_speed = self.avg_start_speed()
print("The average speed of a {} for a {} is {}".format(self.result,self.name ,
avg_start_speed))
#Open pitches.csv outside the class
with open('pitches.csv') as fh:
#Open the csv as a dict and pass it as an argument to Pitch
spreadsheet = csv.DictReader(fh)
p1 = Pitch("CH", "S", spreadsheet)
p1.myfunc()
因此,如果pitches.csv
看起来像
start_speed,end_speed,type,pitch_type
92.9,84.1,S,CH
94.1,85.2,S,CH
输出将为
The average speed of a S for a CH is 93.5