Home > front end >  Name Error- name "xxxxx" is not defined with the objects - Python
Name Error- name "xxxxx" is not defined with the objects - Python

Time:02-13

Am very new to Python programming.Which am getting the naming error in my function with the object but without the object it works fine.

Hope to get a help from the community.

--Code works
def determine_grade(TestScore):
     print("test")
def Mainfunction():
     test1 = float(input('Enter the score for test 1: '))
     print("Your Grade for Test 1 is : ",determine_grade(test1))
Mainfunction() 

--Code doesnot works

class clsCalcScore_Ex6(object):

def determine_grade(TestScore):
     print("test")
def Mainfunction():
     test1 = float(input('Enter the score for test 1: '))
     print("Your Grade for Test 1 is : ",determine_grade(test1))
Mainfunction(object)
     

CodePudding user response:

The minimal problem with your code is that your definition of the class clsCalcScore_Ex6 is incomplete. If you add a single line to fully define the class, like this, your code will work:

class clsCalcScore_Ex6(object):
    pass

If what you want to do is move your functions into the class as methods, then you have more work to do. Here's what doing that correctly might look like:

class clsCalcScore_Ex6(object):

    def determine_grade(self, TestScore):
         print("test")

    def Mainfunction(self):
         test1 = float(input('Enter the score for test 1: '))
         print("Your Grade for Test 1 is : ", self.determine_grade(test1))

clsCalcScore_Ex6().Mainfunction()

Here's another way that uses static methods and avoids you having to instantiate an instance of the class (note the removal of the first set of parens in the last line):

class clsCalcScore_Ex6(object):

    @staticmethod
    def determine_grade(TestScore):
         print("test")

    @staticmethod
    def Mainfunction():
         test1 = float(input('Enter the score for test 1: '))
         print("Your Grade for Test 1 is : ", clsCalcScore_Ex6.determine_grade(test1))

clsCalcScore_Ex6.Mainfunction()

The second way is functionally identical to your original code. It just adds a namespace, placing most of your code under the name clsCalcScore_Ex6.

  • Related