bob gailer wrote:
<div class="moz-text-flowed" style="font-family: -moz-fixed">Megan Land wrote:

All three methods are defined below the snippet I provided.


In Python names must be defined before they are referenced. Put these defs above the snippet.


def func():
code...
def func0():
do stuff
def func1():
do stuff
def func2():
do stuff

Megan Land
FVT Blade EMET Test Engineer
[email protected]

Inactive hide details for Kent Johnson ---08/13/2009 05:18:10 PM---On Thu, Aug 13, 2009 at 3:30 PM, Megan Land<[email protected] Johnson ---08/13/2009 05:18:10 PM---On Thu, Aug 13, 2009 at 3:30 PM, Megan Land<[email protected]> wrote: > Hi,


From: Kent Johnson <[email protected]>

To: Megan Land/Raleigh/Contr/i...@ibmus

Cc: [email protected]

Date: 08/13/2009 05:18 PM

Subject: Re: [Tutor] Dynamic Function Calls

Sent by: [email protected]

------------------------------------------------------------------------



On Thu, Aug 13, 2009 at 3:30 PM, Megan Land<[email protected]> wrote:
> Hi,
>
> I'm trying to call a function from a dictionary. I did some googling and > from what I can tell my code should work, but doesn't. Here's an example:
>
> def myFunc(self, inputList):
> dict={0: func0, 1: func1, 2:func2}
> for element in inputList:
> dict[element]()
>
> When I go to run this I get an error saying func0 is not defined. Does
> anyone have any ideas as to why this won't work? I'm using Python 2.6 if
> that makes any difference.

You don't show any definition for func0 in the above snippet. Where is
it defined?

Kent

------------------------------------------------------------------------

_______________________________________________
Tutor maillist  -  [email protected]
http://mail.python.org/mailman/listinfo/tutor

You can put these defs in any order. But when you invoke the function from your outerlevel code, all of them need to have been defined. I'm guessing you had these in this order:

<code>
def myFunc(self, inputList):
   dictionary={0: func0, 1: func1, 2:func2}
   for element in inputList:
       dictionary[element]()    ...

myFunc(3, 1, 2, 1) #this is too early in the file, because the following defs have not been defined yet

def func():
    code...
def func0():
   do stuff
def func1():
   do stuff
def func2():
   do stuff

#move the call to myFunc() here
</code>


Move the outerlevel code to the end, and you're usually better off. You also might want to put it inside an
if __name__ == "__main__":

clause.


Note, I also changed the variable 'dict' to 'dictionary,' since dict already has a meaning in Python. Not a big deal in this particular case, but if you ever wanted to convert a list to a dict, and called dict(), you'd wonder what went wrong. Better to kill the habit early.

DaveA

_______________________________________________
Tutor maillist  -  [email protected]
http://mail.python.org/mailman/listinfo/tutor

Reply via email to