Truzen
Truzen

Reputation: 29

How to properly implement a list as a instance variable?

So I'm reading through An Introduction to Programming Using Python and doing the exercises for my own edification. I'm learning about custom classes and get to a part where it states: "The program should use a class named Quizzes that has an instance variable to hold a list of the six grades..." So I tried the following:

class Quizzes:

    def __init__(self, grade1=0):
        self._grade1 = grade1

    def setGrade1(self, grade1):
        self._grade1 = grade1

    def getGrade1(self):
        return self._grade1

    def grades(self):
        return []

    def gradeInsert(self, a=grades()):
        a.append(self._grade1)

In this case, I get "TypeError: grades() missing 1 required positional argument: 'self'.

I've also tried:

   def __init__(self, grade1=0, grades=[]):
       self._grade1 = grade1
       self._grades = grades

   def setGrade1(self):
       self._grade1 = grade1

   def setGrades(self):
       self._grades = [self.getGrade1()]

   def getGrades(self):
       return self._grades

But I get a blank [ ]. Any modification I do to grades=[ ] in _ init _ reflects in my getGrades call. So how do I get setGrades to actually set? Or am I totally off the mark?

Upvotes: 0

Views: 481

Answers (2)

achimh
achimh

Reputation: 382

In your first example you try to call grades() which is a member function of the Quizzes class. Member functions expect the instance as the first argument, either before the dot (the_instance.grades()) or as (less common) as an explicit argument (grades(the_instance)). You provide neither and thus Python complains.

In your second example it is not clear what you actually do after the class is defined.

In general, the two classes do not have much to do with the exercise, which would be solved by the following:

class quizzes(object):
  def __init__(self, grades = None):
    if grades is None:
      self.grades = [0]*6
    else:
      self.grades = grades[:6]

BTW: it is not recommended to use a mutable object as default argument as this object is shared between all invocations.

Upvotes: 2

Silvio Mayolo
Silvio Mayolo

Reputation: 70297

Instance variables should be initialized inside of __init__

class Quizzes:

    def __init__(self):
        self._grades = [] # Here, we initialize the list

    def grades(self):
        return self._grades # We can return the instance variable here

    def gradeInsert(self, a): # No reason for a default argument here
        self._grades.append(a) # Add the value to the list

Upvotes: 4

Related Questions