Home > Software engineering >  NameError: name 'mobile' is not defined
NameError: name 'mobile' is not defined

Time:09-09

class mobile:
    def __init__(self,brandname,color,isjack):

        self.brand=brandname
        self.color=color
        self.isjack=isjack

    def calling(self):
        print('calling')

    def cameraclick(self):
        print('picture is clicked')

    def message(self):
        print('message_sent')

    def main():

        m1=mobile('apple','black',False)
        print(m1.brand)
        print(m1.color)
        print(m1.isjack)
        m1.calling()
        m1.cameraclick()
        m1.message()   

        print("-------------------")

        m2=mobile('samsung','grey',False)
        print(m2.brand)
        print(m2.color)    
        print(m2.isjack)
        
    if __name__=='__main__':
        main()

I wrote a basic code to check why was i getting the name error. if anyone could help?

CodePudding user response:

Check your indentation. As it is right now, your main function is a (static) method of your mobile class. This means that method and everything inside it gets read before the class definition for mobile is complete. Thus, the interpreter does not "know" mobile yet.

You should also reduce the indentation for this:

if __name__ == '__main__':
    main()

CodePudding user response:

how are u doing?

This is happening bcs of indentation mistakes on the code!

Python uses indentation to indicate a block of code.

if main lives inside class mobile block it will only be callable if u prepend it with the mobile keyword when calling it

So u need to unindent the def main(): and if __name__ == '__main__': method and to the root level.

class Mobile:
    def __init__(self, brandname, color,isjack):
        self.brand=brandname
        self.color=color
        self.isjack=isjack

    def calling(self):
        print('calling')

    def cameraclick(self):
        print('picture is clicked')

    def message(self):
        print('message_sent')

def main():
    m1 = Mobile("apple", "black", False)
    print(m1.brand)
    print(m1.color)
    print(m1.isjack)
    m1.calling()
    m1.cameraclick()
    m1.message()

    print("-------------------")

    m2 = Mobile("samsung", "grey", False)
    print(m2.brand)
    print(m2.color)
    print(m2.isjack)

if __name__=='__main__':
    main()

tip:

  • ur class should ne named under the PascalCase rules
  • Related