本文介绍了当我的python函数存在于同一文件中时,为什么未定义它?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的函数,我将其称为myFunction.它使用两个参数,对它们执行一些计算,然后返回结果.

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

我还有一个类MyClass,该类的构造函数的标题如下:

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

如果删除此类,则可以在Python Shell中使用myFun,这有什么用?

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

推荐答案

您没有显示实际的代码,因此很难确定,但是我敢打赌myFunction是在MyClass之后定义的.定义__init__方法时将评估默认值表达式,因此必须在此时定义myFunction.以后定义它为时已晚.

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.

这篇关于当我的python函数存在于同一文件中时,为什么未定义它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-05 09:13