Python 这是什么__初始;你在这个代码里做什么?
我不理解以下代码:Python 这是什么__初始;你在这个代码里做什么?,python,lambda,Python,Lambda,我不理解以下代码: def __init__(self, create_context=None): self._events = [] self._create_context = ( create_context if create_context is not None else lambda *_: nop_context ) class nop_context(object): """A nop cont
def __init__(self, create_context=None):
self._events = []
self._create_context = (
create_context
if create_context is not None else
lambda *_: nop_context
)
class nop_context(object):
"""A nop context manager.
"""
def __enter__(self):
pass
def __exit__(self, *excinfo):
pass
我知道self.\u create\u context是一个生成器,但是self.\u create\u context在执行init之后会保持什么?生成器表达式中的lambda是做什么的?如果将其分为两行,则更容易判断:
create_context if create_context is not None
else lambda *_: nop_context
(注意:这不是我刚才所说的有效语法)
self.\u create\u context
将是create\u context
如果create\u context
不是None
,但是如果它是None
,那么我们需要使用默认值。本例中的默认值是一个lambda函数,它将*.
作为参数,并返回nop\u上下文
<代码>*.一开始可能有点混乱,但它与*args
相同:这意味着我们可以接受任意数量的参数。我们将把这些参数存储在一个名为的元组中。这里使用了。
,因为我们不打算使用这些参数。不管它们是什么,我们总是返回nop_context
那段代码非常简洁。我会用更明确的东西
def __init__(self, create_context=None):
if create_context:
self._create_context = create_context
else:
self._create_context = lambda *_: nop_context
可以说,如果create\u context不是None,我应该尊重相同的:
,这取决于create\u context通常是什么(我假设它是一些可调用的,稍后可以调用它来懒洋洋地创建上下文)。self.\u create\u context
不是生成器,除非create\u context
参数中传递的值恰好是生成器。否则,括号只是包装表达式,以便它可以跨多行,这可能是为了提高可读性
但是,此函数所做的全部工作是将默认值应用于self.\u create\u context
。基本上与此相同:
class nop_context(object):
def __enter__(self):
pass
def __exit__(self, *excinfo):
pass
def __init__(self, create_context=lambda *_: nop_context):
self._events = []
self._create_context = create_context
*.
只是一种允许函数接受任意数量参数的方法。我更喜欢用*args
代替*.
,因为这是一种更容易识别的Python习惯用法
注意:当定义了\uuuu init\uuu
方法时,我上面展示的方法为类创建了一个lambda函数。严格来说,函数是可变的。这意味着对函数对象的任何更改都将影响相应类的所有实例。这与使用列表等可变默认值时类似。虽然在列表的情况下可能会出现问题,但修改函数一点也不常见,因此它不应该成为问题。是另一个类的\uuuu init\uuu
函数,还是有错误的顺序?