Explanation of Instance Variables in Python

Bengt Richter bokr at oz.net
Wed Apr 28 21:10:21 EDT 2004


On Wed, 28 Apr 2004 11:25:08 -0700, David MacQuigg <dmq at gain.com> wrote:

>
>I am writing a chapter for teaching OOP in Python.  This chapter is
>intended as a brief introduction to replace the more complete
>discussion in Learning Python, 2nd ed, pp. 295-390.  I need to explain
>instance variables.
>
>What I'm looking for is the best compromise between brevity and a full
>explanation.  The students are non-CIS technical professionals (
>engineers and scientists ).  At the point they need this explanation,
>they have covered functions and modules, but not classes.  They are
>new to object-oriented programming.  They have just been shown a class
>definition with some data attributes and methods.
>
>The non-CIS background is important, because I can't assume any
>experience with other computer languages.
>
>I would like to hear from users who have a similar background, or
>anyone who has taught such users.  What is your background?  Which of
>the alternatives below do you like or dislike?  Can you think back on
>your own learning experience, and write something better?
>
>Here are some alternatives I have collected:
>
[... snip ...]
>
>=====================================
>
>Thanks for your help on this project.
>
I find well-annotated examples best for understanding something new.
It also gives me working code to play with, to explore variations.
How things break is often as instructive as how they work.

I would suggest you encourage your students to experiment interactively.
E.g., ask who can explain the following, and see what you get, and then
collaborate with them to write sufficient comments to where they feel
they "get it."

 >>> class C(object): pass
 ...
 >>> def f(*args): print 'f was called with', args
 ...
 >>> f('hello')
 f was called with ('hello',)
 >>> c=C()
 >>> c.f('hi')
 Traceback (most recent call last):
   File "<stdin>", line 1, in ?
 AttributeError: 'C' object has no attribute 'f'
 >>> c.f = f
 >>> c.f('hi')
 f was called with ('hi',)
 >>> C.f = f
 >>> c.f('greetings')
 f was called with ('greetings',)
 >>> del c.f
 >>> c.f('greetings')
 f was called with (<__main__.C object at 0x00901330>, 'greetings')

MRO can wait a little ;-)

Regards,
Bengt Richter



More information about the Python-list mailing list