Instance variables question

Peter Otten __peter__ at web.de
Mon Apr 16 14:45:28 EDT 2018


Chris Angelico wrote:

> On Tue, Apr 17, 2018 at 3:34 AM, Peter Otten <__peter__ at web.de> wrote:
>> 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()
>>
>> This style is rather brittle. Consider the following variant:
>>
>>>>> class A:
>> ...     x = ""
>> ...
>>>>> a = A()
>>>>> b = A()
>>>>> a.x += "a"
>>>>> a.x += "a"
>>>>> b.x += "b"
>>>>> a.x
>> 'aa'
>>>>> b.x
>> 'b'
>>>>> A.x
>> ''
>>
>> Seems to work. Now let's change x to something mutable:
>>
>>>>> A.x = []
>>>>> a = A()
>>>>> b = A()
>>>>> a.x += "a"
>>>>> a.x += "a"
>>>>> b.x += "b"
>>>>> a.x
>> ['a', 'a', 'b']
>>>>> b.x
>> ['a', 'a', 'b']
>>>>> A.x
>> ['a', 'a', 'b']
>>
>> Conclusion: don't do this except to learn how attributes work in Python.
> 
> Be careful: Your example looks nice and tidy because you're adding
> single-character strings onto a list. They happen to work as you'd
> expect. Normally, though, if you're adding onto a list, you probably
> want to use another list:
> 
> a.x += ["a"]
> 
> But you've successfully - if partly unwittingly - shown how hairy this can
> be :)

That was not an accident -- it was an attempt to make the two examples look 
as similar and harmless as possible. If the use of strings as a sequence 
distracts you use tuples instead:

>>> class A:
...     x = ()
... 
>>> a = A()
>>> b = A()
>>> a.x += "alpha",
>>> a.x += "alpha",
>>> b.x += "beta",
>>> a.x
('alpha', 'alpha')
>>> b.x
('beta',)
>>> A.x
()
>>> A.x = []
>>> a = A()
>>> b = A()
>>> a.x += "alpha",
>>> a.x += "alpha",
>>> b.x += "beta",
>>> a.x
['alpha', 'alpha', 'beta']
>>> b.x
['alpha', 'alpha', 'beta']
>>> A.x
['alpha', 'alpha', 'beta']




More information about the Python-list mailing list