[Tutor] Unbound methods

François Granger francois.granger@free.fr
Wed Nov 20 17:23:02 2002


At 2:10 +0200 21/11/02, in message [Tutor] Unbound methods, am@fx.ro wrote:
>Hello all!
>
>I am new to both python and this list.
>
>I am trying to write my first silly script containing a class
>with a few methods (this script might become someday a part
>of a WAV player):
>
>class WavSet:
>     def __init__(self):
>         print 'Init'
>     def open(self):
>         print 'Open'
>     def close(self):
>         print 'Close'
>     def play(self,wav_id):
>         print 'Play %d'%(wav_id,)
>
>w=WavSet
>print w.open()
>print w.close()
>
>I got an error that i don't understand:
>TypeError: unbound method must be called with class instance 1st argument

Python 2.2.2 (#138, Oct 25 2002, 23:10:42)  [CW CARBON GUSI2 THREADS GC] on mac
Type "copyright", "credits" or "license" for more information.
>>>  class WavSet:
     def __init__(self):
         print 'Init'
     def open(self):
         print 'Open'
     def close(self):
         print 'Close'
     def play(self,wav_id):
         print 'Play %d'%(wav_id,)

w=WavSet
print w.open()
print w.close()

... ... ... ... ... ... ... ... ... >>> >>> Traceback (most recent call last):
   File "<stdin>", line 1, in ?
TypeError: unbound method open() must be called with WavSet instance 
as first argument (got nothing instead)
>>>  Traceback (most recent call last):
   File "<stdin>", line 1, in ?
TypeError: unbound method close() must be called with WavSet instance 
as first argument (got nothing instead)
>>>  >>> w=WavSet()
Init
>>>  print w.open()
Open
None
>>>  print w.close()
Close
None
>>>

the line w=WavSet bind the name w to the WavSet class but does not 
create an instance of the class.
You could use w instead of WavSet anywhere.

The line w=WavSet() create an instance of WavSet and bind this 
instance to w. Then you can call methodes on w.

HTH
-- 
Le courrier électronique est un moyen de communication. Les gens devraient
se poser des questions sur les implications politiques des choix (ou non
choix) de leurs outils et technologies.
Pour des courriers propres : http://minilien.com/?IXZneLoID0 - 
http://marc.herbert.free.fr/mail/ http://expita.com/nomime.html