python - 名称错误 : global name 'myExample2' is not defined # modules

标签 python class python-3.x module

这是我的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 文件时,出现以下错误:

NameError: global name 'myExample2' is not defined

我该如何解决?

最佳答案

这是对您的代码的一个简单修复。

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

关于python - 名称错误 : global name 'myExample2' is not defined # modules,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19998190/

相关文章:

python - python 3 是否有任何 linux 发行版?

c# - 登录后发送数据到其他表单C#

class - Powershell 5 类的 Pester 模拟方法

Python:以随机顺序删除一对重复的字符串

python - Scrapy 从任何网站获取所有链接

python - Django 管理表单可以使用跨站请求伪造 (CSRF) 进行操作

python - Python 中的重定向打印 : val = print(arg) to output mixed iterable to file

python - 循环范围结束后自动销毁变量

c++ - typedef 包含模板化类的共享指针

python-3.x - cairosvg 已安装但导入错误