Why is my python function not defined when it exists in the same file?

I have a simple function that I will call myFunction . It takes two parameters, performs some calculations on them and returns the result.

I also have a MyClass class that has a constructor with the following title:

 __init__(self, bar, fun=myFunction): 

When I try to run something in this class, I get the following error:

 MyClass def __init__(self, bar, fun=myFunction): NameError: name 'myFunction' is not defined 

If I remove this class, I can use myFun in the Python Shell, so what's the deal?

+4
source share
2 answers

You did not specify the actual code, so it’s hard for you to be sure, but I’m sure that myFunction is defined after MyClass . The default expression is evaluated when defining the __init__ method, so myFunction must be defined at this point. Defining it later is too late.

+10
source

myFunction is a variable, not a value, so you cannot use it as a default parameter.

Perhaps you could use the lambda function as the default parameter instead of the name of the declared function.

-6
source

All Articles