gpt4 book ai didi

python - 在类和函数中工作

转载 作者:行者123 更新时间:2023-11-28 22:54:59 26 4
gpt4 key购买 nike

快速提问...我一直在开发一个小程序,该程序将根据“家庭作业”、“测验”和“测试”以及获得的字母等级来计算最终成绩百分比。这是一个我正在测试新事物的程序,我想知道如何在类里面或类内使用所有这些?

我考虑过保持功能性的东西不变,只使用一个类来基本上打印出学生姓名、最终字母等级和百分比的漂亮字符串。即使在类里面进行简单的打印,我也无法引入外部数据。有什么想法吗?

另外,有没有办法让用户的输入创建全新的空字典? (也许如果可以创建多个词典,我可以创建一个函数或方法来计算类(class)平均值)我感谢您的帮助。谢谢!

student1 = {}
student = [student1]
def maker_d():
name = raw_input("Please enter the student's name: ")
student1['Name'] = name
homework = raw_input("Please enter all of the student's homework grades separated by a space: ")
homework = [float(i) for i in homework.split()]
student1['homework']= homework
quizzes = raw_input("Please enter all of the student's quiz scores separated by a space: ")
quizzes = [float(i) for i in quizzes.split()]
student1['quizzes'] = quizzes
tests = raw_input("Please enter all of the student's test scores separated by a space: ")
tests = [float(i) for i in tests.split()]
student1['tests'] = tests


def average(student):
return sum(student) / len(student)

def get_average(student):
h = average(student['homework'])
q = average(student['quizzes'])
t = average(student['tests'])
total_average = (h * 0.1) + (q * 0.3) + (t * 0.6) #designates homework as 10%, quizzes as 30% and tests as 60% of final grade average
return total_average


def get_letter_grade(score):
if score >= 90:
return "A"
elif 80<= score <90:
return "B"
elif 70 <= score < 80:
return "C"
elif 60 <= score < 70:
return "D"
else:
return "F"


def get_class_average(student):
total = 0
for each in student:
total += get_average(each)
return total / len(student)
return get_class_average(get_average[student])

class FinalGradePrinter(object):


def __init__(self,name):
self.name = name
def __str__(self,name):
print "% ',' your final grade is a %s based on your overall percentage of %f" % (self.name)



def main():
maker_d()
print get_class_average(student)
print get_letter_grade(get_class_average(student))



if __name__ == '__main__':
main()

最佳答案

类是您要在应用程序中使用的对象的模板,对象旨在通过封装“事物”的属性来封装“事物”,以及使用这些属性的函数(例如,计算基于属性值,更改它们等)。这个主题太复杂了,这里不做更多介绍,值得对面向对象编程进行一些研究。

在您的情况下,您肯定有将 Student 作为类的情况,这是您代码中具有属性的“事物”,以及使用这些属性的函数。下面是您创建自己的 Student 类的一个很好的起点 - 尝试填写该类并修改您的代码以使用它(这将需要学习面向对象编程)将是一个很好的练习。随着示例的增长,您可能还想为测验、测试和家庭作业创建类。

class Student:

# Constructor
def __init__(self, name, homework, quizzes, tests):
self.name = name
self.homework = homework
self.quizzes = quizzes
self.tests = tests

# Function to return average for this student
def get_average(self):
h = average(self.homework)
...
return total_average

祝你好运,玩得开心!

关于python - 在类和函数中工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17442567/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com