user2907700 user2907700 - 1 month ago 15
Python Question

Python error: NameError: name 'ClassName' is not defined

I am new to python. I am getting error while running this class. Not sure what the problem is:

class BubbleSort:


def __init__(self,arrays):
self.a=arrays


def BubblesortFunction(self):
for i in range(0,len(self.a),1):
for j in range(0,len(self.a)-i-1,1):
if(self.a[j]>self.a[j+1]):
temp=self.a[j]
self.a[j]=self.a[j+1]
self.a[j+1]=temp

def printTheArray(self):
for i in self.a:
print(i,end=" ")

def main():
a=[7,2,3,4,1,6,8,9,5]
obj1= BubbleSort(a)
obj1.BubblesortFunction()
obj1.printTheArray()

if __name__=='__main__': main()





Output:

Traceback (most recent call last):
File "/Users/sudhir/PycharmProjects/untitled/Sample/BubbleSort.py", line 1, in <module>
class BubbleSort:
File "/Users/sudhir/PycharmProjects/untitled/Sample/BubbleSort.py", line 26, in BubbleSort
if __name__=='__main__': main()
File "/Users/sudhir/PycharmProjects/untitled/Sample/BubbleSort.py", line 22, in main
obj1= BubbleSort(a)
NameError: name 'BubbleSort' is not defined


Note: when I run the same code without the main() function and the "if name=='main': main()" statement it works fine. I just write these statements at the end of the class :

a=[7,2,3,4,1,6,8,9,5]
obj1= BubbleSort(a)
obj1.BubblesortFunction()
obj1.printTheArray()

Answer

This is indentation error, and the main() function must be called outside the class.

class BubbleSort:


    def __init__(self,arrays):
        self.a=arrays


    def BubblesortFunction(self):
        for i in range(0,len(self.a),1):
            for j in range(0,len(self.a)-i-1,1):
                 if(self.a[j]>self.a[j+1]):
                     temp=self.a[j]
                     self.a[j]=self.a[j+1]
                     self.a[j+1]=temp

    def printTheArray(self):
        for i in self.a:
            print(i,end=" ")

def main():
    a=[7,2,3,4,1,6,8,9,5]
    obj1= BubbleSort(a)
    obj1.BubblesortFunction()
    obj1.printTheArray()

if __name__=='__main__': 
    main()
Comments