Python NameError (def) is not defined [duplicate]

泪湿孤枕 提交于 2019-12-19 09:27:04

问题


I'm having trouble with the following Python code:

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

When I run this code, I get NameError: name 'method1' is not defined. How do I resolve this error?


回答1:


Just add self. in front of it:

self.method1(1)

Also change your method signitures to:

def method1(self, n):

and

def method2(self, n):



回答2:


Change your code like following:

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. Add a self parameter to every methods inside of your class
  2. To call a method inside of your class use self.methodName(parameters)
  3. To make instance of your class you should write class name with paranteses for ex: m = Methods()


来源:https://stackoverflow.com/questions/43647515/python-nameerror-def-is-not-defined

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!