Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I access inherited variables from another module when they are changed in parent?

I have a file a.py

avariable = None

class a():

  def method(self):
    global avariable
    avariable = 100
    print "variable is", avariable

and a file b.py

from a import *

class b(a,):

  def mymethod(self):
    a().method()
    print "avariable is " , avariable

if __name__ == '__main__':
  b().mymethod()

File b imports everything from a and also inherits from a. a's method is called and the avariable is change to 100 but when I print avariable in b the value is None. How to I use in class b the variable avariable that a class changed?

Output:

>python b.py 
variable is 100
avariable is  None

Clarification

It's crucial for me to use

from a import *

because I have already code in class b that calls methods of class a using the syntax

self.method()

and that cannot change.

i.e.

from a import *
class b(a):

  def mymethod(self):
    self.method()
    print "avariable is " , avariable

if __name__ == '__main__':
  b().mymethod()

So is there a way to access the variable avariable in a without prefixing in any way the avariable?

like image 991
user847988 Avatar asked Mar 22 '23 01:03

user847988


1 Answers

a.py

avariable = None

class a():

    def method(self):
        global avariable
        avariable = 100
        print "variable is", avariable

b.py

import a


class b(a.a):
    def mymethod(self):
        a.a().method()
        print "avariable is ", a.avariable


if __name__ == '__main__':
    print a.avariable
    b().mymethod()
    b().mymethod()

Output:

None
variable is 100
avariable is  100
variable is 100
avariable is  100

You get None all the time because once you import avariable you keep it in your own file, but what a.py is changing, is the avariable variable in its own file (or more appropriately, its own global namespace), and thus, you can see no change.

But in the example above, you can see the changes. This is because, we are importing the a module itself, and thus accessing all its objects (everything in Python is an object). And thus, when we call a.avariable we are actually calling the avriable variable in a's global namespace.

EDIT

The code below will still produce the same output.

import a


class b(a.a):
    def mymethod(self):
        self.method()
        print "avariable is ", a.avariable


if __name__ == '__main__':
    print a.avariable
    b().mymethod()
    b().mymethod()
like image 116
Games Brainiac Avatar answered Apr 24 '23 23:04

Games Brainiac