这是我在尝试了一个小时之后的第一个python迷你项目。我以前没有编码经验,我直接跳到python类。我想知道,该代码是否有任何改进?
class student:
def __init__(self,name,grade,section):
self.name = name
self.grade = grade
self.section = section
def elon_marks(self):
english = "89"
math = "90"
science = "99"
print("elon scored" , english, "in english")
print("elon scored" , math, "in maths")
print("elon scored" , science, "in science")
def bill_marks(self):
english = "55"
math = "34"
science = "22"
print("bill scored" , english , "in english")
print("bill scored" , math, "in maths")
print("bill score" ,science, "in science")
elon = student("elon","9th","D")
bill = student("bill","11th","A")
elon.elon_marks()
bill.bill_marks()发布于 2022-08-31 16:04:49
在类中编写特定于对象(elon,bill)的函数是错误的。你的课也应该是为第三个学生而写的(还有成千上万的学生)。
关于如何改进您的课堂的一些提示:
__init__函数中添加一行: self.marks = {} # Empty dictionary sub set_mark(self, subject, mark):
self.marks[subject] = markelon = Student("elon","9th","D")
elon.set_mark("english", 55)
elon.set_mark("math", 34)
elon.set_mark("science", 22)
elon.print_marks()发布于 2022-08-31 16:08:40
您可以这样做,这样可以使您的代码更容易阅读,也可以以许多不同的方式使用这个类。
class Student:
def __init__(self, name, grade, section):
self.name = name
self.grade = grade
self.section = section
self.marks = {}
def insert_new_mark(self, subject, mark):
if subject not in self.marks:
self.marks.update({subject: mark})
else:
print("Subject is already in marks")
elon = Student("elon", "9th", "D")
bill = Student("bill", "11th", "A")
elon.insert_new_mark("English", 89)
elon.insert_new_mark("Math", 90)
elon.insert_new_mark("Science", 99)
bill.insert_new_mark("English", 55)
bill.insert_new_mark("Math", 34)
bill.insert_new_mark("Science", 22)
print(elon.marks)
print(bill.marks)产出:
{'English': 89, 'Math': 90, 'Science': 99}
{'English': 55, 'Math': 34, 'Science': 22}https://stackoverflow.com/questions/73558505
复制相似问题