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

余生颓废 提交于 2019-12-18 08:54:31

问题


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

I also have a class, MyClass, which has a constructor that has a header like this:

__init__(self, bar, fun=myFunction):

When I try to run anything 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?


回答1:


You haven't shown the actual code so it's hard to be sure, but I bet myFunction is defined after MyClass. The default value expression is evaluated when the __init__ method is defined, so myFunction must be defined at that point. Defining it later is too late.




回答2:


myFunction is a variable, not a value so you can't use it as a default parameter.

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



来源:https://stackoverflow.com/questions/11165423/why-is-my-python-function-not-defined-when-it-exists-in-the-same-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!