Mic*_*ael 8 python module class python-3.x
这是我的example.py档案:
from myimport import *
def main():
myimport2 = myimport(10)
myimport2.myExample()
if __name__ == "__main__":
main()
Run Code Online (Sandbox Code Playgroud)
这是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
Run Code Online (Sandbox Code Playgroud)
当我运行example.py文件时,我有以下错误:
NameError: global name 'myExample2' is not defined
Run Code Online (Sandbox Code Playgroud)
我该如何解决这个问题?
我在你的代码中看到两个错误:
myExample2如self.myExample2(...)self在定义myExample2时添加:def myExample2(self, num): ...这是对代码的简单修复.
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()
Run Code Online (Sandbox Code Playgroud)
而且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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
58371 次 |
| 最近记录: |