[Tutor] Syntax when using classes question.

Alan Gauld alan.gauld at btinternet.com
Sat Nov 11 12:59:48 CET 2006


>    pyForge.promptForge.prompt()
> TypeError: unbound method prompt() must be called with promptForge 
> instance
> as first argument (got nothing instead)
> ^ Thats why... I have to use :
> import pyForge
> pyForge.promptForge().prompt()

I think the real issue that Luke was raising was why you are using 
that style.
Basically you are creating an instance of pyForge just to call the 
then it gets deleted again (by garbage collection). Thats a very 
function call!

The normal usage of classes and objects is that you create an
instance and retain it, thus:

myForge = pyForge.promptForge()
# and use it again

Thus the myForge instance is retained until you are finished using
any of the methods.

The reason for that is that the instance will hold the data used
by the methods and so if you delete it you delete the data too!
For examplein your case you could have promptForge hold the
prompt message you want to display. That could nbe initialised
in the constructor, thus you could have several promptForge
instances each with a different prompt message, lie this:

class promptForge:
    def __init__(self.,msg = "? "):
       self.message = msg
       self.value = None  # stores last input value
   def prompt(self):
        print self.message,
        self.value = raw_input()
        return self.value

And use it thus:

yes_no = promptForge("Continue? [Y/N] ")
quit = promptForge("Hit Y to quit")
intValue = promptForge("Enter an integer between 0 and 9")

if yes_no.prompt() in "yY":
    for n in range(3):
        x = int(intValue.prompt())
        print x
        if quit.prompt() in "yY2: break

But if you don't have any internal data, you don;t really
need instances...

Now it looks like you have created some classes with no
shared data just functions(methods). In that case you would
be better just using functions inside the module. Its easier to
use and also has a lower resource usage and potentially
lower call overhead (no method lookup/dispatch)


Alan Gauld
Author of the Learn to Program web site

More information about the Tutor mailing list