Class Definitions

Alan Bawden alan at csail.mit.edu
Thu Nov 12 14:47:38 EST 2020


ram at zedat.fu-berlin.de (Stefan Ram) writes:

     I expected this solution:

   class Main:
       def __init__( self ):
           self.value = 0
       def count( self ):
           self.value += 1

     but a student turned in the following solution:

   class Main:
       value = 0
       def count(self):
           self.value += 1

     I thought that the solution of the student had a shortcoming
     but I was not able to put my finger on it. Can you?

Not exactly a shortcoming, but the fact that it works as a solution to
your problem may cause the student to someday write something like:

  class Main:
      value = []
      def add(self, x):
          self.value += [x]

and be suprised by the resulting behavior.

-- 
Alan Bawden


More information about the Python-list mailing list