Search code examples
pythonfunctionvariablesprogram-entry-point

How to retrieve value of objects/ variables from one function to another and calling the two functions by main?


I am trying to get values from kindle() and process them in bundle() and call these two functions in main, but i get the error: NameError: name 'x' is not defined at the bundle()'s first line, while x is declared globally.

class Program:

    x = 0
    y = 0
    def kindle(self):
        x = 2
        y = 3
    return x, y

    def bundle(self):
        z = x+ y
        print(z)

def main():
    p = Program()
    p.kindle()
    p.bundle()
if __name__ == "__main__":
    main()

Solution

  • Ah, a discussion of classes. So, the x and y you defined "globally" are not really global, they are class objects and accessed from the class. For example,

    class thing:
        x = 10
        def func(self):
            print(thing.x)
    

    Notice that the "x" is attached to the class "thing". Hence, "x" is not global. In general, anything inside of a class is accessed through the class and is not apart of the outside space.

    Of course, one of the MAIN benefits of using classes is that all the functions and variables share a common namespace. An instance of this namespace is referred to as "self" and is passed around automatically to all class functions. Hence, doing "thing.x" is completely unnecessary (and requires that I know the name of the class). Instead we can do:

    class thing:
        x = 10
        def func(self):
            print(self.x)
    

    We can go further of course. If I can access self at all times in a class, then if I attached to the self, other functions will be able to see that attachment automatically. Lets try:

    class Program:
    
        x = 0 #Default value if we don't overwrite. 
        y = 0 #Default value if we don't overwrite. 
    
        def kindle(self):
            self.x = 2 #Overwrote the default. 
            self.y = 3 #Overwrote the default. 
            #No need to return anything. Self already has x and y attached.
    
        def bundle(self):
            z = self.x + self.y
            print(z)
            #z is not attached to self, hence z is only available in this function. 
    
    def main():
        p = Program() #Create an instance of the Program class. 
        p.kindle()    #Overwrite the default x and y values for just this instance.
        p.bundle()    #Add the values and print. 
    
    if __name__ == "__main__":
        main()