Instance variables question

Peter Otten __peter__ at web.de
Mon Apr 16 13:34:00 EDT 2018


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.




More information about the Python-list mailing list