This came up on Chris99's bus ticket program thread. Would like to see any simple examples on how to pass variables between classes without using global variables.

As an example I pulled the basics out of the bus ticket program. Here is the original global variable version ...

class Main(object):
    def __init__(self, master):
        self.master = master
        self.display()
        
    def display(self):
        global p
        global pp
        p = 2.20
        pp = 0.50
        # variables p and pp are passed as global variables
        # to class Child
        child = Child()
        
class Child(object):
    def __init__(self):
        global p
        global pp
        pr = p * pp
        print 'final price =', pr     #  final price = 1.1
        
main = Main('dummy')

Since the class Child instance is created within class Main it would be tough for class Child to inherit class Main, that would lead to runaway recursion. So the prudent way to avoid global variables would be to pass the proper variables on as instance arguments to class Child ...

class Main(object):
    def __init__(self, master):
        self.master = master
        self.display()
        
    def display(self):
        self.p = 2.20
        self.pp = 0.50
        # to make self.p and self.pp available to class Child
        # pass them on as instance arguments
        child = Child(self.p, self.pp)
        
class Child(object):
    def __init__(self, p, pp):
        pr = p * pp
        print 'final price =', pr     # final price = 1.1

        
main = Main('dummy')
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.