codehaus


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

Class Definitions


On 11/14/2020 4:09 AM, Manfred Lotz 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.

It was not.  But self.x as a value, rather than a target, first looks 
for instance x, then class x, then superclass x, up to object.x.  Such 
lookup is routine for methods, much rarer for data.

self.value += 1 is roughly equivalent to
self.value = self.value +1 where the right self.value is Main.value. 
'self' is only looked up once, but apparently the value attribute is 
looked up twice, in spite of what one might think from the doc, so that 
the first assignment to self.value initializes an instance value rather 
than overwriting the class value.

-- 
Terry Jan Reedy