[Tutor] Function output

Remco Gerlich scarblac@pino.selwerd.nl
Tue, 27 Jun 2000 12:27:04 +0200


On Mon, Jun 26, 2000 at 10:51:42PM -0500, William Perry wrote:

> First I need to thank everyone for taking time to answer, I'm alittle
> embarrested to admit that the terminology I used in the original question
> was incorrect. What I'm actually trying to do is get method output from a
> class. ( Thanks to the first set of answers I have the functions operating
> correctly as functions) I think that the suggestion of including the problem
> code is the best way to ' re-ask'. And again thanks for the help.
>
> >From Idle screen: 
> 
> >>> class rollum:
>  def funct1 (self):
>   s = " Hello World"
>   return s
>  def output (self):
>   a = funct1()
>   return a
>  
>  
> >>> rollum.output()
> Traceback (innermost last):
>   File "<pyshell#42>", line 1, in ?
>     rollum.output()
> TypeError: unbound method must be called with class instance 1st argument

Ahh, but this is another problem. You must make an instance of the class
first and then use that.

You see, a class is a kind of "blueprint" for an object. It can't be used by
itself, but you use it to make instances of the class, and you can use those.

So try:

>>> r = rollum()      # make an instance
>>> r.output()        # call the method on the instance

But that still won't work, since the output function uses a function
funct1(), but doesn't know where to find it. You have to tell it to look in
"self":

>>> class rollum:
   def funct1(self):
      return "Hello World"
   def output(self):
      a = self.funct1()
	  return a

>>> r = rollum()
>>> r.output()

I hope this clears it up a bit.

(Inside the method, "self" is now a reference to r, btw)


-- 
Remco Gerlich,  scarblac@pino.selwerd.nl