How to access variable outside class in my example?

17,285

Solution 1

You simply reference it; you don't need any special global permission to access it. This isn't the best way, but since you haven't described your application and modularity requirements, about all we can do right now is to solve your immediate problem.

By the way, your a, b, c references are incorrect. See below.

class testing():
    def __init__(self, a, b, c):
        self.a = a
        self.b = b
        self.c = c
        self.greeting = module

    def house(self):
        d = self.a + self.b + self.c
        print d
        print self.greeting

module="hello"
p = testing(1, 2, 3)
p.house()

Output:

6
hello

Solution 2

You could use globals(). But I'm not sure if this is good idea at all.

class testing():
    def __init__(self, a, b, c):
        self.a = a
        self.b = b
        self.c = c

    def house(self):
        print(globals()['module'])
        d = self.a + self.b + self.c
        print(d)


module = 'here'
t = testing(1, 2, 3)
t.house()

Output:

# here
# 6

Solution 3

Maybe I don't understand the question, it already works since the global variable "module" is defined before you instantiated the class.

class testing():
    def __init__(self, a, b, c):
        self.a = a
        self.b = b
        self.c = c

    def house(self):
        d = self.a+self.b+self.c
        print module
        print d

module="hello"
p = testing(1, 2, 3)
p.house()

outputs:

hello

6

Share:
17,285
david
Author by

david

Updated on June 05, 2022

Comments

  • david
    david almost 2 years
    class testing():
        def __init__(self, a, b, c):
            self.a = a
            self.b = b
            self.c = c
    
        def house(self):
            d = self.a+self.b+self.c
            print d
    
    module="hello"
    p = testing(1, 2, 3)
    p.house()
    

    How do I access module variable from within my testing class? I know I could just add it as a parameter to the class constructor by doing:

    p=testing(1,2,3,module)
    

    But I don't want to do that unless I have to. What other ways can I access module variable from inside the testing class?