Issue
I am new to python. Base class/python file(Base.py).
SESSION_ID = ""
def m1():
print "SESSION_ID in base: ",SESSION_ID
Derived class(Derived.py)
from Base import *
class Derived():
def m2(self):
global SESSION_ID
SESSION_ID = 10
print "SESSION_ID in derived: ", SESSION_ID
def main():
c2 = Derived()
c2.m2()
m1()
if __name__ == "__main__":
main()
When I execute Derived.py file below is the output:
SESSION_ID in derived: 10
SESSION_ID in base:
I want the value which is set in m2() to be reflected in m1(). So the expected output is:
SESSION_ID in derived: 10
SESSION_ID in base: 10
Can you please help?
Solution
The global variable in a module is merely an attribute (i.e. a member entity) of that module.
As result of that when you use import *
, the new local module global SESSION_ID
is created, so the SESSION_ID in the base is immune to the changes you are doing in the Derived.
Basically, modifying base.SESSION_ID
don't require usage of the global
statement in the Derived.py
, adjusting import
is enough, see code below:
from settings import base
class Derived():
def m2(self):
base.SESSION_ID = 10
print "SESSION_ID in derived: ", base.SESSION_ID
def main():
c2 = Derived()
c2.m2()
base.m1()
if __name__ == "__main__":
main()
Answered By - Andriy Ivaneyko
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.