在尝试使用类和方法以及如何在类和方法之间传递变量的同时,我编写了一些脚本来尝试理解机制。 这样做时,我遇到了一个问题,即我的功能之一未定义:
NameError: name 'exclaim' is not defined
我以为使用自我可能会解决,但我只是四处探寻
NameError: name 'self' is not defined
关于这一点,我遇到了许多资料,这使我着眼于方法的缩进级别,并通过HelloWorld.exclaim()进行调用 遇到同样的问题。
请参阅我的代码:(script1)
import datasource
class HelloWorld:
def exclaim():
number1 = input("enter a number")
datasource.Class2.method3.impvariable1 = number1
def main():
HelloWorld.exclaim()
print(datasource.Class1.method1.variable1)
print(datasource.Class2.method2.variable2)
print(datasource.Class2.method3.variable3)
if __name__ == '__main__':
main()
脚本2:
#datasource.py
class Class1:
def method1():
variable1 = "Hello "
class Class2:
def method2():
variable2 = "World"
def method3():
impvariable1 = 0
variable3 = "!"
for x in range(impvariable1):
variable3 = variable3 + "!"
我也尝试过(其他迭代次数为100)
#datahandler.py
import datasource
class HelloWorld:
def exclaim(self):
number1 = input("enter a number")
datasource.Class2.method3.impvariable1 = number1
def main(self):
HelloWorld.exclaim(self)
print(datasource.Class1.method1.variable1)
print(datasource.Class2.method2.variable2)
print(datasource.Class2.method3.variable3)
if __name__ == '__main__':
main(self)
产生;
NameError: name 'self' is not defined
答案 0 :(得分:2)
import datasource
class HelloWorld:
def exclaim(self):
number1 = input("enter a number")
datasource.Class2.method3.impvariable1 = number1
def main():
obj = HelloWorld()
obj.exclaim()
print(datasource.Class1.method1.variable1)
print(datasource.Class2.method2.variable2)
print(datasource.Class2.method3.variable3)
if __name__ == '__main__':
main()