Skip to main content
 首页 » 编程设计

python之Python中的NameError之无法调用函数

2025年05月04日8haluo1

这个问题在这里已经有了答案:





module import: NameError: name is not defined

(3 个回答)


4年前关闭。




我是 Python 新手。在我的模块 Utility.py 中,下面的函数接受一个人的年龄和性别。它会根据此人的年龄和性别退还此人必须支付的费用。我不允许对此模块进行任何更改。

def get_fees(age, gender): 
    if gender == 'M': 
        if age >= 50: 
            return 300  
        elif age >= 35: 
            return 250 
        else: 
            return 150 
    else: 
        if age >= 50: 
            return 320 
        elif age >= 35: 
            return 270 
        else: 
            return 160 

我还创建了一个新模块 PrintFees.py,我需要在其中提示用户年龄和性别,然后将输入传递给我需要从实用程序模块调用的函数 (get_fees)。我还需要打印所需的费用。

这是我尝试过的:
import Utility 
age= int(input("What's your age? " )) 
gender = input("What's your gender? [M|F]") 
#Print fees  
print("Your fees is $", Utility.get_fees(age,gender)) 

当我尝试运行时,出现了此错误消息。
Traceback (most recent call last): 
File "printfees.py", line 7, in <module> 
print("Your fees is $", Utility.get_fees(age,gender)) 
NameError: name 'Utility' is not defined 

我该如何解决这个问题?谢谢。

请您参考如下方法:

首先,您需要在与您的代码相同的文件夹中或在 python 目录中的站点包中的 Utility 模块。如果它是实用程序代码中类的名称。我将展示一个例子:

import Utility 
Utility.className.functionName(arguments)