小编Pét*_*eéh的帖子

为类中的方法实现就地操作

pandas很多方法中都有关键字参数inplace。这意味着 if inplace=True,被调用的函数将在对象本身上执行,并返回 None ,另一方面,如果inplace=False原始对象将保持不变,则在返回的新实例上执行该方法。我已经成功地实现了这个功能,如下所示:

from copy import copy

class Dummy:
    def __init__(self, x: int):
        self.x = x

    def increment_by(self, increment: int, inplace=True):
        if inplace:
            self.x += increment
        else:
            obj = copy(self)
            obj.increment_by(increment=increment, inplace=True)
            return obj

    def __copy__(self):
        cls = self.__class__
        klass = cls.__new__(cls)
        klass.__dict__.update(self.__dict__)
        return klass
    
if __name__ == "__main__":
    a = Dummy(1)
    a.increment_by(1)
    assert a.x == 2
    b = a.increment_by(2, inplace=False)
    assert a.x == 2
    assert b.x == 4
Run Code Online (Sandbox Code Playgroud)

它按预期工作。但是,我有很多方法可以重复相同的模板:

def …
Run Code Online (Sandbox Code Playgroud)

python decorator in-place

6
推荐指数
1
解决办法
126
查看次数

标签 统计

decorator ×1

in-place ×1

python ×1