How do I import a variable from another function in the same class

class W(object):
    #my class
    def variable(self):
        #one of my functions
        f = 5
    def printf(self):
        #what do i put here to import f from the function variable...
        #I'm currently working with python 3.1.
        #I know its not global f and for some reason when ever I try
        #nonlocal f an error comes up saying "no binding for nonlocal "f" found"
        #and highlights the first line...
        print(f)
    def main(self):
        self.variable()
        self.printf()

if __name__ == "__main__":
    n  = W()
    n.main()

Recommended Answers

All 2 Replies

You need to use the 'self' keyword. So inside the function variable, you'd say self.f = 5 . Then when you call printf, you'd say print(self.f) .

By not making the variable a property of the class by using 'self', you're just making it in the local scope of the function. And, when you call a class' functions from within itself, you also need to attach 'self' in front. Like if within a function on class W, you wanted to make a call to its printf function, you'd use self.printf() .

Here's is the documentation about scopes and name spaces regarding classes in Python:
http://docs.python.org/tutorial/classes.html#python-scopes-and-name-spaces.

Hope that helped!

Thank you soooo very much... spent 2 hours last night trying to update my python program but i couldn't with out that piece of info....

Thanks again..

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.