[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Class Definitions

On 13/11/2020 08:47, Alan Bawden wrote:
> ram at (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.

You are right to be concerned - although largely because the differences 
between class-variables and instance-variables is (sadly) one of those 
topics poorly-understood by many, and thus best avoided simply to 
prevent confusion. (I'll be the first to concur that this not a good 
reason, and particularly not for someone in education/training, but 
that's life ["as we know it, Jim"])

A worthwhile read is:

(including @Alan's most-pertinent warning of the subtleties introduced 
by mutable data-structures)

On the other hand, Python has long?always had an aversion to the 
object-induced 'boiler-plate' required in other languages - and I have 
to say, even building Python classes with __init__(), __str__(), and 
__repr__()  etc "magic methods", can seem a slog for low return-value.

AFTER teaching/learning about the 'classic form', you may like to 
consider DataClasses (Python 3.7+). These look very similar to your 
student's submission. One of their objectives is to cut-through a load 
of the boiler-plate - in many circumstances.

See also Counter Objects:
Regards =dn