Write a class Student() such that it has an attribute 'score' (that is initialized with 10) and three methods: add_score(): adds 10 to the score decrease_score(): decreases score by 10 __str__(): returns the current score (should return a string) Example:

Answer :

mahamnasir

Answer:

I am writing the Python program. Let me know if you want the program in some other programming language. Here is the Python code:

class Student(object):

   def __init__(a,score=10):

       a.score=score

   def add_score(a,score):

       a.score += 10

       return (score)

   def decrease_score(a,score):

       a.score -=10

       return (score)

   def __str__(a):

       current_score="{}".format(a.score)

       return current_score

Explanation:

The program has a Student() class with attribute score.

It has the following methods:

__init__(): This method works as a constructor and enables to initialize score attribute of Student class. The value of score is initialized to 10. I have used a as the instance of Student class. However self keyword can also be used as an instance of the object to access the attributes and methods of Student class.

add_score() This method is used to add 10 to the score.

decrease_score() This method is used to decrease the score by 10.

__str__() This method is used to return the current score. format() is used here to return a string. current_score holds the value of the current score.

If you want the check the working of the program, then you can use the following statements to see the results on the output screen:

p = Student()

print(p)

p.add_score(p)

print(p)

This will create an object p of Student class and calls the above methods to display the values of the score according to the methods.

The program along with its output is attached.

${teks-lihat-gambar} mahamnasir
MrRoyal

Classes in Python are used as a layout to create objects.

The Student() class in Python, where comments are used to explain each line is as follows:

#This defines the Student class

class Student(object):

   #The following function initializes score to 10

   def __init__(scr,score=10):

       scr.score=score

   #The following function increases score by 10

   def add_score(scr,score):

       scr.score += 10

       return scr

   #The following function decreases score by 10    

   def decrease_score(scr,score):

       scr.score -=10

       return scr

   #The following function returns the current score as a string    

   def __str__(scr):

       current_score = scr.score

       return current_score

Read more about Python classes at:

https://brainly.com/question/20728426

Other Questions