[Tutor] Calling a function within a function within a class...

Alan Gauld alan.gauld at btinternet.com
Sat Nov 10 10:17:05 CET 2007


"Trey Keown" <trey at opmstech.org> wrote

> I'm creating a module for my program, and I need to call a function.
> Here's how it's set up:
> -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
> class DoStuff:
>    def Thing1(self):
>        def ThingToCall(self):
>            print "It worked!"
>    def Thing2(self):
>        #Call the function "ThingToCall" here.
> -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
> Thanks for any help. I haven't used classes that much before...

This doesn't have much of anything to do with classes.
The same happens if you just use functions:

def f(x):
   def g(x):
      print 'in g'

You cannot call g() outside of f() because it is not visible
You need to return g to make it visible outside f, like this:

def f(x):
   def g(x):
      print 'in g'
   return g

Now you can call g() by doing:

myG = f(42)
myG(25)

or

f(42)(25)

So in your class example, if you add a return to
Thing1 you could do:

d = DoStuff()
f = d.Thing1()
f()

BTW Its usually a sign of bad OO design to have a
class name that is a verb, objects are things so
should be named with nouns. The methods should
be named with verbs - they *do* stuff to things.
So you class would be more conventional if it was

class Thing:
    def doStuff1()
    def doStuff2()

That then allows you to extend your program using
subclassing and polymorphism which in turn usually
saves you some coding. Classes named after verbs
usually wind up with very long if/elif chains inside
each method which is slow and hard to maintain.

However there are occasional cases where it makes
sense, and your may be one of those exceptions.
Just a thought.

HTH

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld 




More information about the Tutor mailing list