为什么CPython代码中有时会有模式:obj_method = obj.method?

问题描述 投票:3回答:1

我想知道使用它的原因是什么,这种模式什么时候提供帮助。

集合模块中有几个示例:

def _count_elements(mapping, iterable):
    'Tally elements from the iterable.'
    mapping_get = mapping.get
    for elem in iterable:
        mapping[elem] = mapping_get(elem, 0) + 1

https://github.com/python/cpython/blob/2fecb48a1d84190c37214eb4b0c8d5460300a78b/Lib/collections/init.py#L480


    if iterable is not None:
        if isinstance(iterable, _collections_abc.Mapping):
            if self:
                self_get = self.get
                for elem, count in iterable.items():
                    self[elem] = count + self_get(elem, 0)

https://github.com/python/cpython/blob/2fecb48a1d84190c37214eb4b0c8d5460300a78b/Lib/collections/init.py#L631

python cpython
1个回答
2
投票

在这两个示例中,这样做都是出于性能原因。称为“。”对象上的运算符需要在对象的属性集中查找属性/方法(例如,上例中的get)。通过将方法分配给新变量(例如self_get,您无需在每次迭代中进行此查找。)

© www.soinside.com 2019 - 2024. All rights reserved.