gpt4 book ai didi

python - 是否可以在Python中定义一个新的数学运算符?

转载 作者:行者123 更新时间:2023-12-01 00:27:56 25 4
gpt4 key购买 nike

是否可以定义我自己的数学运算符?

喜欢新的介绍@PEP-465用于矩阵乘法或 //对于 integer division .

类似的东西

a ! b -> a / (a + b)

最佳答案

您可以使用尚未针对整数实现的预定义运算符之一。

例如这个:@ (matmul)

您不能使用 ! 字符,因为它不在此 list 中.

class MyInt(int):
def __matmul__(self, other):
return self / (self + other)

然后你可以这样做:

a = MyInt(1)
b = MyInt(2)
print(a @ b)

将打印 (0.33333333)

关于python - 是否可以在Python中定义一个新的数学运算符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58411150/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com