0

I need to pass a value created within a class method to a function, or procedure or def or whatever it is called, in the 'main program'

global myValue

class CalcFrame(object):
        def clearFunc(self):
                myValue = 12

def getUrl():
        print myValue

This was my idea, obviously it does not work:

I do that code, then I create an object

x = CalcFrame()

call the method which should set the global

x.clearFunc()

then call the function which should print it

getUrl()

get the error

NameError: global name 'myValue' is not defined

BartoszKP
  • 34,786
  • 15
  • 102
  • 130
Ryan
  • 782
  • 1
  • 10
  • 25

1 Answers1

7

This is not how the global keyword is used.

It should be used this way instead

myValue = None

class CalcFrame(object):
    def clearFunc(self):
            global myValue
            myValue = 12

In a nutshell, global allows a function to modify a variable that exists in the global scope. See here for more info: https://docs.python.org/2/faq/programming.html#what-are-the-rules-for-local-and-global-variables-in-python

Uyghur Lives Matter
  • 18,820
  • 42
  • 108
  • 144
Anthony Kong
  • 37,791
  • 46
  • 172
  • 304