【问题标题】:Allow python objects to interact with mathematical operators [duplicate]允许python对象与数学运算符交互[重复]
【发布时间】:2020-05-17 17:15:56
【问题描述】:

我问它是因为我记得 numpy 是用数组做的。我应该添加两个包含单项式的对象。

另外,是否可以创建自定义数学运算符? (就像numpy点积的@)

【问题讨论】:

    标签: python python-3.x operators custom-operator


    【解决方案1】:

    这是很有可能的。类可以包含允许对象与+ 和其他运算符交互的“魔术方法”。具体来说,文档的this 部分是相关的,尽管快速阅读整个文档会很有帮助。

    该链接中最相关的方法:

    object.__add__(self, other)
    object.__sub__(self, other)
    object.__mul__(self, other)
    object.__matmul__(self, other)
    object.__truediv__(self, other)
    object.__floordiv__(self, other)
    object.__mod__(self, other)
    object.__divmod__(self, other)
    

    例如,@ 可以通过实现__matmul__ 方法来使用:

    class T:
        def __matmul__(self, other_t):
            pass
    
    print(T() @ T())
    

    您不能创建该语言中尚不存在的“自定义”运算符,但您可以利用现有运算符中的任何挂钩。

    【讨论】:

    • 非常感谢,这非常有用!第二个问题呢,有可能吗?
    • @Giuppox 查看我最近的编辑。
    猜你喜欢
    • 1970-01-01
    • 2017-01-16
    • 1970-01-01
    • 2021-01-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多