Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fix "NameError: name method-name is not defined"? [duplicate]

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?

like image 535
maestro777 Avatar asked Apr 27 '17 02:04

maestro777


People also ask

How do I fix my NameError in Python?

The Python "NameError: name is not defined" occurs when we try to access a variable or function that is not defined or before it is defined. To solve the error, make sure you haven't misspelled the variable's name and access it after it has been declared.

Why am I getting a NameError in Python?

What Is a NameError in Python? In Python, the NameError occurs when you try to use a variable, function, or module that doesn't exist or wasn't used in a valid way. Some of the common mistakes that cause this error are: Using a variable or function name that is yet to be defined.


2 Answers

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):
like image 125
Peter Pei Guo Avatar answered Oct 20 '22 03:10

Peter Pei Guo


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()
like image 39
Siamand Avatar answered Oct 20 '22 04:10

Siamand