Class Definitions

2QdxY4RzWzUUiLuE at potatochowder.com 2QdxY4RzWzUUiLuE at potatochowder.com
Sat Nov 14 06:08:07 EST 2020


On 2020-11-14 at 10:09:32 +0100,
Manfred Lotz <ml_news at posteo.de> wrote:

> On 11 Nov 2020 19:21:57 GMT
> ram at zedat.fu-berlin.de (Stefan Ram) wrote:
> 
> >   In my Python course I gave the assignment to define a
> >   counter class "Main" so that
> > 
> > counter0 = Main()
> > counter1 = Main()
> > counter1.count(); counter1.count(); counter1.count()
> > counter1.count(); counter1.count()
> > print( counter0.value )
> > print( counter1.value )
> > 
> >   would print
> > 
> > 0
> > 5
> > 
> >   .
> > 
> >   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 am still a Python beginner and didn't even believe that the student's
> solution would work. I had expected an error as the instance variable
> self.value was not initialized.

Remember:  (1) x += 1 behaves like x = x + 1, and (2) bindings created
inside a class statement but outside any method create class attributes.

So after counter0 = Main(), Main (the class) has an attribute called
"value" whose value is 0, and counter0.value refers to that attribute.

Then counter0.count() executes self.value += 1, which behaves like
self.value = self.value + 1.  The right side of that assignment
evaluates to 1 (the value of the class attribute plus the constant 1),
and then the assignment statement initializes self.value to *that*
value.

There's nothing special about initializing instance attributes in
__init__.  An instance attribute can be created/initialized anywhere.

HTH,
Dan


More information about the Python-list mailing list