Python – main method in Python

python

I have the following code, which has the following two problems:

Traceback (most recent call last):
  File "C:\Users\v\workspace\first\src\tests.py", line 1, in <module> 
  class Animal:
  File "C:\Users\v\workspace\first\src\tests.py", line 39, in Animal

  File "C:\Users\v\workspace\first\src\tests.py", line 31, in main
    dog = Animal()
NameError: global name 'Animal' is not defined

This code is from a tutorial, and in the tutorial it works fine. I have the Python 2.7 and use the PyDev plugin for Eclipse.

  class Animal:
    __hungry = "yes"
    __name = "no name"
    __owner = "no owner"

    def __init__(self):
        pass

    def set_owner(self,newOwner):
        self.__owner= newOwner
        return

    def get_owner(self):
        return self.__owner

    def set_name(self,newName):
        self.__name= newName
        return

    def get_name(self):
        return self.__name

    def noise(self):
        print('errr')
        return

    def __hiddenmethod(self):
        print("hard to find")


    def main():
        dog = Animal()    
        dog.set_owner('Sue')
        print dog.get_owner()
        dog.noise()


    if  __name__ =='__main__':main()

Best Answer

This code:

def main():
    dog = Animal()    
    dog.set_owner('Sue')
    print dog.get_owner()
    dog.noise()


if  __name__ =='__main__':main()

should not be in the class. When you take it outside (no indent) it should work.

So after taking that into account it should look like this:

class Animal:
    __hungry = "yes"
    __name = "no name"
    __owner = "no owner"

    def __init__(self):
        pass

    def set_owner(self,newOwner):
        self.__owner= newOwner
        return

    def get_owner(self):
        return self.__owner

    def set_name(self,newName):
        self.__name= newName
        return

    def get_name(self):
        return self.__name

    def noise(self):
        print('errr')
        return

    def __hiddenmethod(self):
        print("hard to find")


def main():
    dog = Animal()    
    dog.set_owner('Sue')
    print dog.get_owner()
    dog.noise()


if  __name__ =='__main__':
    main()