如何修复“NameError:name methodname未定义”?

2024-06-07 00:09:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我在使用以下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: name 'method1' is not defined.

如何解决此错误


Tags: 代码nameinnumberformaindefmore
2条回答

更改代码,如下所示:

class Methods:

    def method1(self,n):
        #method1 code

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

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

if __name__ == '__main__':
    main()
  1. 向类中的每个方法添加一个self参数
  2. 要在类内部调用方法,请使用self.methodName(参数)
  3. 要创建类的实例,您应该为ex:m=Methods()编写带有paranteses的类名

加上自我。在它前面:

self.method1(1)

同时将方法符号更改为:

def method1(self, n):

def method2(self, n):

相关问题 更多 >