关于Python中的with语句的两个问题。他们来自现实生活中的问题,所以我保持真实。我正在处理一个夹管阀,以便控制管道中的流量。你知道吗
程序驱动阀门的类如下所示:
class Valve(object):
"""This class drives a pinch valve."""
def __init__(self):
self.close()
def open(self):
print('Open the valve.')
self.state = 'opened'
def close(self):
print('Close the valve.')
self.state = 'closed'
def print_state(self):
print('The valve is '+self.state+'.')
对于某些操作,我需要with语句对文件执行的操作(文件在结尾处关闭或引发错误时关闭),因此我向类Valve和另一个类添加了一个函数:
def opened(self):
return ContextManagerOpenedValve(self)
class ContextManagerOpenedValve(object):
def __init__(self, valve):
self.valve = valve
def __enter__(self):
self.valve.open()
return self.valve
def __exit__(self, type, value, traceback):
self.valve.close()
然后这些线条似乎和我预期的一样:
def do_something():
print('For the sake of simplicity, this function does nothing.')
valve = Valve()
valve.print_state()
with valve.opened():
valve.print_state()
do_something()
valve.print_state()
我的第一个问题:怎样才能取得这样的结果?我使用with语句对吗?如果不定义ContextManageRopedValve类,我就不能用更聪明的方法来实现吗?你知道吗
然后我需要这样做: 使用_VALVE=False#或使用_VALVE=True
if USE_VALVE:
with valve.opened():
do_something()
else:
do_something()
我不喜欢这个解决方案,因为dou something函数无论如何都在运行,所以最好避免重复“dou something()”。你知道吗
我的第二个问题是:有没有一种方法可以不加限制地获得同样的结果 重复做某事()两次?你知道吗
当然,你可以这样做:
你的电话看起来像:
相关问题 更多 >
编程相关推荐