NameError:全局名称"myExample2"未定义#模块 [英] NameError: global name 'myExample2' is not defined # modules

查看:87
本文介绍了NameError:全局名称"myExample2"未定义#模块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的example.py文件:

from myimport import *
def main():
    myimport2 = myimport(10)
    myimport2.myExample() 

if __name__ == "__main__":
    main()

这是myimport.py文件:

class myClass:
    def __init__(self, number):
        self.number = number
    def myExample(self):
        result = myExample2(self.number) - self.number
        print(result)
    def myExample2(num):
        return num*num

运行example.py文件时,出现以下错误:

When I run example.py file, i have the following error:

NameError: global name 'myExample2' is not defined

我该如何解决?

推荐答案

下面是对代码的简单修复.

Here's a simple fix to your code.

from myimport import myClass #import the class you needed

def main():
    myClassInstance = myClass(10) #Create an instance of that class
    myClassInstance.myExample() 

if __name__ == "__main__":
    main()

myimport.py:

class myClass:
    def __init__(self, number):
        self.number = number
    def myExample(self):
        result = self.myExample2(self.number) - self.number
        print(result)
    def myExample2(self, num): #the instance object is always needed 
        #as the first argument in a class method
        return num*num

这篇关于NameError:全局名称"myExample2"未定义#模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆