未定义Python NameError(def)[重复]


问题内容

这个问题已经在这里有了答案

如何在类中调用函数?
(2个答案)

去年关闭。

我在使用以下Python代码时遇到了麻烦:

class Methods:

    def method1(n):
        #method1 code

    def method2(N):
        #some method2 code
            for number in method1(1):
                #more method2 code

def main():
    m = Methods
    for number in m.method2(4):
            #conditional code goes here

if __name__ == '__main__':
    main()

运行此代码时,出现NameError:未定义名称“ method1”。如何解决此错误?


问题答案:

只是添加自我。在它前面:

self.method1(1)

还将您的方法签名更改为:

def method1(self, n):

def method2(self, n):