我是python的新手。 基类/ python文件(Base.py)。
SESSION_ID = ""
def m1():
print "SESSION_ID in base: ",SESSION_ID
派生类(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()
当我执行以下Derived.py文件时,输出为:
SESSION_ID in derived: 10
SESSION_ID in base:
我希望将在m2()中设置的值反映在m1()中。所以预期的输出是:
SESSION_ID in derived: 10
SESSION_ID in base: 10
可以帮忙吗?
答案 0 :(得分:3)
模块中的全局变量仅是一个属性(即一个成员 实体)。
因此,当您使用import *
时,将创建新的全局本地模块SESSION_ID
,因此基础中的SESSION_ID不受您在“派生”中所做的更改的影响。
基本上,修改base.SESSION_ID
不需要使用global
中的Derived.py
语句,调整import
就足够了,请参见下面的代码:
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()
答案 1 :(得分:2)
您的Derived
类不是{strong>不是派生自Base.py
内部的任何东西。在这里,您只是在Base
中从Derived
调用基本功能,仅此而已。
这是Python3中class inheritance上的一个示例:
>>> class Base():
>>> SESSION = 42
>>>
>>> def print_session(self):
>>> print("Base session : %d" % self.SESSION)
>>>
>>> class Derived(Base):
>>> SESSION = 999
>>>
>>> d = Derived()
>>> d.print_session()
Base session : 999
答案 2 :(得分:1)
如果可能,我将避免使用全局变量和类作用域变量。这些会使您的程序更难于理解(如果其他什么改变了您下面的全局,很难注意到)和测试(您需要在每次测试之间重置所有全局状态;通常更容易创建新的空状态)。
我可以通过创建一个状态对象来重组此示例:
class State:
def __init__(self):
self.session_id = ''
然后将其明确地设为基类的属性:
class Base:
def __init__(self, state):
self.state = state
def m1(self):
print("SESSION_ID in base: " + str(self.state.session_id))
class Derived(Base):
def m2(self):
self.state.session_id = '10'
print("SESSION_ID in derived: " + str(self.state.session_id))
然后在主函数中,您需要显式创建状态对象并将其传递给
def main():
state = State()
c2 = Derived(state)
c2.m2()
c2.m1()
但是,至关重要的是,您的测试无需担心状态泄漏
def test_m2():
state = State()
obj = Derived(state)
obj.m2()
assert state.session_id == '10'
def test_m1():
state = State()
obj = Base(state)
obj.m1()
# If the session ID was a global or a class variable,
# you'd get a different result if m2() was called or not
assert state.session_id == ''