小编drm*_*ttu的帖子

在 Python 中使用 __getattr__ 重载运算符

我试图使用该__getattr__函数同时重载多个运算符。在我的代码中,如果我调用foo.__add__(other)它,它会按预期工作,但是当我尝试时foo + bar,它不会。这是一个最小的例子:

class Foo():
    
    
    def add(self, other):
        return 1 + other
    
    def sub(self, other):
        return 1 - other
    
    def __getattr__(self, name):
                
        stripped = name.strip('_')
        if stripped in {'sub', 'add'}:
            return getattr(self, stripped)
        else:
            return
    
if __name__=='__main__':
    
    bar = Foo()
    
    print(bar.__add__(1)) # works
    print(bar + 1) # doesn't work
Run Code Online (Sandbox Code Playgroud)

__add__我意识到在此示例中仅定义和会更容易__sub__,但在我的情况下这不是一个选项。

另外,作为一个小问题,如果我替换该行:

if stripped in {'sub', 'add'}:
Run Code Online (Sandbox Code Playgroud)

if hasattr(self, name):
Run Code Online (Sandbox Code Playgroud)

代码可以运行,但随后我的 iPython 内核崩溃了。为什么会发生这种情况以及如何预防?

python

5
推荐指数
1
解决办法
541
查看次数

标签 统计

python ×1