Explanation of Instance Variables in Python

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


On 29 Apr 2004 01:10:21 GMT, bokr at oz.net (Bengt Richter) wrote:

>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.
You might want to mention early that they are a special subset
of object attributes, and that understanding the Python rules for accessing
attributes in general is critical to understanding its implementation of OOP.
>>
>>=====================================
>>
>>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."
>
Actually, looking at my previous example, maybe this would give more hints,
in case they don't discover for themselves (strongly urge teaching how to
fish, not serving fish, though ;-):

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

Regards,
Bengt Richter



More information about the Python-list mailing list