python中声明方法(&self)的问题

问题描述 投票:-2回答:1

在尝试使用类和方法进行实验以及如何在它们之间传递变量时,我编写了几个脚本来尝试理解这些机制。这样做我遇到了一个问题,我的一个函数是未定义的:

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()

SCRIPT2:

#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
python python-3.x class methods self
1个回答
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()
© www.soinside.com 2019 - 2024. All rights reserved.