Please help me to understand classes

Lars Marius Garshol Lars.Marius.Garshol at p98.f112.n480.z2.fidonet.org
Tue Jun 29 22:55:03 EDT 1999


From: Lars Marius Garshol <larsga at ifi.uio.no>


* Johann Spies
| 
| Can somebody explain to me why the following program produces no
| output:

A good trick to learn in Python is that if you use the interpreter you
can fool around and figure things out much more easily and quicker
than if you use something that resembles the edit-compile-run loop of
Pascal.

| [...skipping class defs]
|         
| a = A()
| c = B()
| c.druk
| a.druk

If you do this in the interpreter you get:

>>> a = A()
>>> c = B()
>>> c.druk
<method B.druk of B instance at 80bdd50>
>>> a.druk
<method A.druk of A instance at 809a4d8>

This is a general rule in Python: if you mention a function or method
by name you just get a reference to it. If you add parentheses it is
called. 

>>> c.druk()
Traceback (innermost last):
  File "<stdin>", line 1, in ?
TypeError: no arguments expected
>>> a.druk()
Traceback (innermost last):
  File "<stdin>", line 1, in ?
TypeError: no arguments expected

In your example this failed, since you forgot the self argument. If
you redeclare as:

class A:

    def druk(self):
        print 'Jy is in Class A'

To illustrate:

>>> a=A()
>>> a.druk
<method A.druk of A instance at 80b1e60>
>>> a.druk()
Jy is in Class A
>>> method=a.druk
>>> method
<method A.druk of A instance at 80b1e60>
>>> method()
Jy is in Class A


--Lars M.




More information about the Python-list mailing list