Back

Explore Courses Blog Tutorials Interview Questions
0 votes
1 view
in Python by (108k points)

Here is my example.py file:

from myimport import *

def main():

    myimport2 = myimport(10)

    myimport2.myExample() 

if _name_ == "__main__":

    main()

And here is myimport.py file:

class myClass:

    def __init__(self, number):

        self.number = number

    def myExample(self):

        result = myExample2(self.number) - self.number

        print(result)

    def myExample2(num):

        return num*num

When I run example.py file, I have the following error:

NameError: global name 'myExample2' is not defined

How can I fix that?

1 Answer

0 votes
by (47.6k points)

Follow this simple way to fix your code.

from myimport import myClass 

#import the class you needed

def main():

    myClassInstance = myClass(10) 

    #Create an instance of that class

    myClassInstance.myExample() 

if _name_ == "__main__":

    main()

And the myimport.py:

class myClass:

    def __init__(self, number):

        self.number = number

    def myExample(self):

        result = self.myExample2(self.number) - self.number

        print(result)

    def myExample2(self, num): 

        #the instance object is always needed 

        #as the first argument in a class method

        return num*num

Related questions

0 votes
1 answer
0 votes
1 answer
asked Nov 28, 2020 in Python by ashely (50.2k points)
0 votes
1 answer
0 votes
2 answers
Welcome to Intellipaat Community. Get your technical queries answered by top developers!

28.4k questions

29.7k answers

500 comments

94k users

Browse Categories

...