Я создаю программу, которая берет информацию об учениках и результаты тестов и генерирует графический интерфейс, который вычисляет их среднее значение, медиану, моду и стандартное отклонение. Также требуется наличие кнопки «Показать результаты», которая отображает линейный график результатов тестов учащегося. Однако я продолжаю сталкиваться со следующей ошибкой:
TypeError: StudentView.init() отсутствует 1 обязательный позиционный аргумент: 'студент '
Может кто-нибудь помочь мне понять, что я делаю не так с этим кодом. Я несколько раз пытался сделать это правильно.
Вот коды, с которыми я работаю:
student.py
class Student:
def __init__(self, student_id, name):
self.student_id = student_id
self.name = name
self.test_scores = []
def add_test_score(self, score):
self.test_scores.append(score)
def average_test_score(self):
if len(self.test_scores) == 0:
return 0
return sum(self.test_scores)/len(self.test_scores)
def get_test_scores(self):
return self.test_scores
studentview.py
from breezypythongui import EasyFrame
import matplotlib.pyplot as plt
from student import Student
class StudentView(EasyFrame):
def __init__(self, model, student):
EasyFrame.__init__(self)
self.setSize(500, 200)
self.model = model
self.student = student
student = Student(model.student_id, model.name, model.test_scores)
student_view = StudentView(model, student)
self.addLabel("Mean", row = 0, column = 0)
self.addLabel("Median", row = 1, column = 0)
self.addLabel("Mode", row = 2, column = 0)
self.addLabel("Standard deviation", row = 3, column = 0)
self.meanFld = self.addFloatField(value = 0.0, row = 0, column = 1, precision = 2)
self.medianFld = self.addFloatField(value = 0.0, row = 1, column = 1, precision = 2)
self.modeFld = self.addFloatField(value = 0.0, row = 2, column = 1, precision = 2)
self.stdFld = self.addFloatField(value = 0.0, row = 3, column = 1, precision = 4)
self.addLabel("Data", row = 0, column = 2, sticky = "NEW")
self.scoreArea = self.addTextArea(text = "", row = 1, column = 2, width = 12, rowspan = 3)
bp = self.addPanel(row = 4, column = 0, columnspan = 3, background = "black")
bp.addButton(text = "Edit Score", row = 0, column = 0, command = self.editScore)
bp.addButton(text = "Add score", row = 0, column = 1, command = self.addScore)
bp.addButton(text = "Randomize scores", row = 0, column = 3, command = self.randomizeScores)
bp.addButton(text="Plot Scores", row=0, column=4, command=self.plotScores)
self.refreshData()
def plotScores(self):
scores = self.student.get_test_scores()
positions = list(range(1, len(scores) + 1))
plt.plot(positions, scores, marker='o')
plt.xlabel('Positions')
plt.ylabel('Scores')
plt.title('Student Test Scores')
plt.show()
studentapp.py
"""
File: studentapp.py
The application for editing and analyzing student scores.
"""
from student import Student
from studentview import StudentView
def main():
"""Creates the model and view and starts the app."""
model = Student("Ken", 10)
StudentView(model)
if __name__ == "__main__":
main()
stats.py
"""
File: stats.py
Defines functions to compute the mean, median, std, and mode
of a list of numbers.
"""
import math
import random
def mean(lyst):
"""Returns the mean of a list of numbers."""
return sum(lyst) / len(lyst)
def frequencies(lyst):
"""Returns a dictionary keyed by the unique
numbers and their frequencies in lyst."""
# Obtain the set of unique numbers and their
# frequencies, saving these associations in
# a dictionary
theDictionary = {}
for number in lyst:
freq = theDictionary.get(number, 0)
theDictionary[number] = freq + 1
return theDictionary
def mode(lyst):
"""Returns the mode of a list of numbers."""
theDictionary = frequencies(lyst)
theMaximum = max(theDictionary.values())
for key in theDictionary:
if theDictionary[key] == theMaximum:
result = key
break
return result
def modes(lyst):
"""Returns the modes of a list of numbers."""
# Obtain the set of unique numbers and their
# frequencies, saving these associations in
# a dictionary
theDictionary = frequencies(lyst)
theMaximum = max(theDictionary.values())
result = []
for key in theDictionary:
if theDictionary[key] == theMaximum:
result.append(key)
return result
def median(lyst):
"""Precondition: lyst is non-empty.
Returns the median of numbers in lyst."""
if len(lyst) == 0:
raise RuntimeError("List must be non-empty. ")
copy = list(lyst)
copy.sort()
midpoint = len(lyst) // 2
if len(lyst) % 2 == 1:
return copy[midpoint]
else:
return mean([copy[midpoint - 1], copy[midpoint]])
def std(lyst):
"""Precondition: lyst is non-empty.
Returns the standard deviation of the numbers in lyst."""
if len(lyst) == 0:
raise RuntimeError("List must be non-empty. ")
average = mean(lyst)
differences = map(lambda x: x - average, lyst)
squares = list(map(lambda x: x ** 2, differences))
return math.sqrt(mean(squares))
def getRandomList(size, lower, upper, unique = False):
"""Returns a list of randomly generate numbers
within the given bounds."""
theList = []
for count in range(size):
number = random.randint(lower, upper)
if unique:
while number in theList:
number = random.randint(lower, upper)
theList.append(number)
return theList
def main():
"""Tests the functions."""
lyst = [3, 1, 7, 1, 4, 10]
print("List:", lyst)
print("Mode:", mode(lyst))
print("Median:", median(lyst))
print("Mean:", mean(lyst))
print("Standard deviation:", std(lyst))
print("Frequencies:", frequencies(lyst))
lyst.sort()
print(lyst)
lyst = [3, 1, 7, 1, 4]
print("List:", lyst)
print("Mode:", mode(lyst))
print("Median:", median(lyst))
print("Mean:", mean(lyst))
print("Standard deviation:", std(lyst))
print("Frequencies:", frequencies(lyst))
lyst.sort()
print(lyst)
lyst = getRandomList(10, 1, 10)
print(lyst)
lyst = getRandomList(10, 1, 10, unique = True)
print(lyst)
# The entry point for program execution
if __name__ == "__main__":
main()
Подробнее здесь: https://stackoverflow.com/questions/786 ... ace-that-d
Python: добавление командной кнопки под названием «Построить результаты» в пользовательский интерфейс, которая отображае ⇐ Python
-
- Похожие темы
- Ответы
- Просмотры
- Последнее сообщение