This is my first python mini project after dabbling for one hour. I have zero. nada. previous coding experience, And i directly jumped to python classes. I would like to know , is there any improvement that should be made to the code?
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()
p.s it took me more time to post the code here, than to write the actual code in the ide.
CodePudding user response:
Writing functions that are specific to objects (elon, bill) in your class is wrong. Your class should be written to work for a third student as well (and thousands more).
Some hints on how to improve your class:
- Include marks as your class attributes. Marks can e.g. be stored in a dictionary, where the subject is the key and the mark itself is the value. In your
__init__
function add a line:
self.marks = {} # Empty dictionary
- Add a function to your class to set a mark (you can later improve it to take multiple marks as a list, but here is a simple one:
sub set_mark(self, subject, mark):
self.marks[subject] = mark
Put your print statements into a separate function (e.g. called print_marks). That function shall of course use self.name for the name instead of "elon" or "bill". And instead of printing the marks of three subjects, it should loop (iterate) over what is in the marks dictionary. I leave this as an exercise for you to figure it out.
Adjust your main function accordingly. Example:
elon = Student("elon","9th","D")
elon.set_mark("english", 55)
elon.set_mark("math", 34)
elon.set_mark("science", 22)
elon.print_marks()
CodePudding user response:
You can do something like this that can make your code easier to read and also you can use this class in a lot of different ways
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)
output:
{'English': 89, 'Math': 90, 'Science': 99}
{'English': 55, 'Math': 34, 'Science': 22}