如何将上下文管理器与列表一起使用

时间:2018-04-03 15:08:28

标签: python

我有一个有初始化和清理逻辑的课程:

class Bird(object):
    def __init__(self, name):
        self.name = name

    def __enter__(self):
        print("enter " + self.name)
        return self

    def __exit__(self, type, value, traceback):
        print("exit " + self.name)

我将它与上下文管理器一起使用:

with Bird("chicken") as b:
    print(b)

但是现在我想要使用具有相同行为的对象列表,即在使用list之后,应该处理它的对象:

with DisposableList([Bird("A"), Bird("B")]) as list:
    #some ops

我如何实施清单或其他解决方案?

4 个答案:

答案 0 :(得分:3)

如果您不需要课程

from contextlib import contextmanager
@contextmanager
def bird(lst):
    print 'enter {}'.format(lst)
    yield lst
    print 'exit {}'.format(lst)


with bird([1,2,3,4]) as f:
    print f


enter [1, 2, 3, 4]
[1, 2, 3, 4]
exit [1, 2, 3, 4]

答案 1 :(得分:2)

缠绕一圈:

for bi in ['hawk','chicken','eagle']:
    with Bird(bi) as b:
        print(b)

或者,或许更好的是,使用生成器依次循环遍历Bird对象的每个实例:

def bird_gen(li):
    for bird in li:
        with Bird(bird) as b:
            yield b

for b in bird_gen(['hawk','chicken','eagle']):
    print(b)

答案 2 :(得分:1)

我试图实现自己的列表,看起来很有效。

class DisposableList(list):

    def __enter__(self):
        print("enter list")
        for v in self:
            v.__enter__()
        return self

    def __exit__(self, *exc):
        print("exit list")
        for v in self:
            v.__exit__()


class Bird(object):
    def __init__(self, name):
        self.name = name

    def __enter__(self):
        print("enter " + self.name)
        return self

    def __exit__(self, *exc):
        print("exit " + self.name)


with DisposableList([Bird("A"), Bird("B")]) as ctx:
    print(ctx)

输出:

enter list
enter A
enter B
[<__main__.Bird object at 0x7f9186151668>, <__main__.Bird object at 0x7f9186151780>]
exit list
exit A
exit B

欢迎任何笔记!

答案 3 :(得分:0)

您仍然可以通过为每个<link href="Content/themes/base/jquery-ui.css" rel="stylesheet" /> <link href ="~/Styles/Default.css" rel="stylesheet" /> <script src="../Scripts/jquery-3.3.1.js"></script> <script src="../Scripts/jquery-ui-1.12.1.js"></script> <script> $(document).ready(function() { $("#dd2875").dialog({ buttons: { "Cancel": function() { $("#dd2875").dialog('close'); } }, dialogClass: 'myTitleClass', draggable: false, width: 800, height: 400, hide: 2000, show: 'slidedown', hide: 'explode', autoOpen: false }); $("#btnNewAccount").click(function(evt) { evt.preventDefault(); $("#dd2875").dialog('open'); }); }); </script> 类创建Bird来传递__repr__个对象的列表:

Bird

输出:

class Bird(object):
   def __init__(self, name):
    self.name = name
   def __enter__(self):
     print("enter " + str(self.name))
     return self
   def __exit__(self, type, value, traceback):
     print("exit " + str(self.name))
   def __repr__(self):
     return '{}({})'.format(self.__class__.__name__, self.name)

with Bird([Bird("A"), Bird("B")]) as f:
  print(f)

print('-'*10)
with Bird('chicken') as f:
  print(f)