Python内部类调用外部类的变量,并结合with语法使用
首先, with 语法通过一个 __enter__() 方法和一个 __exit__() 方法,实现自动在某个命令前后执行特定内容,比如,通过 with open() 可以实现在 with 语句结束后 自动close文件句柄 。反正就是 非常方便 了,具体用法可行自行搜索,不是本文重点。
另外,Python支持 类的嵌套 , 内部类 的作用也可以自行再搜索。会发现平时不怎么用,会觉得他很鸡肋,但当用到的时候,就会觉得非常之方便。
这里实现一个功能: 有一个变量,在执行某些操作前后需要设置和撤销该变量的值,以便控制其他线程的运行 。表述的可能不是很明白,直接上一下演示代码:
class Outter:
def __init__(self):
self.allow_thread_running = True
class with_change_ip:
内部类,使用with语法
def __init__(self, father):
内部类初始化函数,构造时自动调用
:param father: 外部类的实例对象
self.father = father
def __enter__(self):
with语法执行前调用
:return:
self.father.allow_thread_running = False
def __exit__(self, type, value, trace):
with语法执行完后调用
:return:
self.father.allow_thread_running = True
def start(self):
print(self.allow_thread_running) # True