python调用函数出现未定义,当我的python函数存在于同一文件中时,为什么未定义它?...

本文探讨了一个问题:在定义类时,如果在构造器`__init__`中使用了未提前定义的函数作为默认参数,会导致NameError。作者解释了原因并提出,函数必须在类定义时就已存在。实例演示了如何修正此类问题。
摘要由CSDN通过智能技术生成

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?

解决方案

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值