NameError: no global name defined when calling a method inside a class

I am trying to call another function inside one class from my main function and I can show where the error is.

I keep getting this error related to undefined functions and I'm not sure how to resolve it:

NameError: global name 'results' is undefined

class Darts:
     def main() :
          print results()

     def results() :
          round_result_totals = "Stuff"
          return round_result_totals

    #RUNNING CODE
    main()

      

+3


source to share


3 answers


Make sure you define correctly self

in your functions and initialize the object first before doing anything else. You cannot just call function

from class

without creating instance

this class

and calling function

from this instance

(NOT THE CLASS). Usually you want to have __init__

python in your classes.

class Darts:
     def __init__(self):
         pass

     def main(self):
          print(self.results())

     def results(self):
          round_result_totals = "Stuff"
          return round_result_totals

Dart1 = Darts()
Dart1.main()

      



If you want to use variables, self

it is also critical for encapsulation.

class Darts:
     def __init__(self):
         self.a = 500

     def main(self):
          self.a += 1
          print(self.a)


Dart1 = Darts()
Dart1.main()

      

+3


source


You need to pass self (an instance of your object) to your object methods.



class Darts:
     def main(self) :
          print self.results()

     def results(self) :
          round_result_totals = "Stuff"
          return round_result_totals

      

+1


source


You are missing all the necessary references self

within your class. It should look like this:

class Darts:
    def main(self) :
        print self.results()

    def results(self) :
        round_result_totals = "Stuff"
        return round_result_totals

      

Here is the Python Class Documentation . And the fifth paragraph of this section refers to the agreement self

.

In short: the first argument of a Python class method is automatically passed in a reference to the instance of that class from which the method is called (assuming it is called as an instance method). This is done automatically using the Python interpreter. However, this parameter must still be explicitly specified in the method definition, and the convention is to name it self

.

+1


source







All Articles