Instance variables question

Irv Kalb Irv at furrypants.com
Mon Apr 16 13:37:02 EDT 2018


> On Apr 16, 2018, at 9:48 AM, duncan smith <duncan at invalid.invalid> wrote:
> 
> On 16/04/18 17:03, Irv Kalb wrote:
>> I have been writing OOP code for many years in other languages and for the past few years in Python.  I am writing new curriculum for a course on OOP in Python.  In order to see how others are explaining OOP concepts, I have been reading as many books and watching as many videos as I can.   I've been watching some videos created by Dr. Chuck Severance in a series called "Python For Everyone".  I think "Dr. Chuck" is an excellent teacher and I think his videos are outstanding.  
>> 
>> Today I watched this video:   https://www.youtube.com/watch?v=b2vc5uzUfoE <https://www.youtube.com/watch?v=b2vc5uzUfoE>  which is about 10 minutes long.  In that video he gives a very basic overview of OOP and classes.  He gives a demonstration using the following example:
>> 
>> class PartyAnimal():
>>    x = 0
>> 
>>    def party(self):
>>        self.x = self.x + 1
>>        print('So far', self.x)
>> 
>> an = PartyAnimal()
>> an.party()
>> an.party()
>> an.party()
>> 
>> # I added this line just to see what it would do
>> print('Class variable', PartyAnimal.x)
>> 
>> 
>> And the output is:
>> 
>> So far 1
>> So far 2
>> So far 3
>> Class variable 0
>> 
>> snip
> 
> My understanding of this:
> 
> x is a class variable.
> 
> Initially an instance has no instance variable self.x. So on the first
> call to self.party the name 'x' is looked up in the class. This value is
> incremented and the result is assigned to self.x. This is where the
> instance variable x is created and set. On subsequent calls to
> self.party there exists an instance variable x, so the name 'x' is not
> looked up in the class.
> 
> Duncan
> -- 
> https://mail.python.org/mailman/listinfo/python-list
> 

Thanks for the responses.  I thought it was something like this, but it hadn't realized that the first time the method was called, the right hand side would access the class variable x, but the second time (and later) it would access the instance variable x.  

I'll stick with the more "standard" approach of assigning the instance variable in the __init__ method.

Thanks,

Irv


More information about the Python-list mailing list