Explanation of Instance Variables in Python

David MacQuigg dmq at gain.com
Fri Apr 30 11:25:19 EDT 2004


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

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

>>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')

I like this example.  It shows clearly how the first argument is
inserted in the calling sequence for a normal method call.  I remember
that seemed very strange when I was learning Python.

-- Dave




More information about the Python-list mailing list