python有float行吗_如何在Python中实现类实例与float和类实例的乘法

我试图用Python编写一个模拟复数的类。是的,我知道已经有一个内置函数

complex()

j

创造他们。但是我想写我自己的只是为了好玩。下面是它的一个小版本:

class Complex:

def __init__(self, real: float = 0, img: float = 0):

self.real = real

self.img = img

self.num = (self.real, self.img)

def __repr__(self) -> str:

string = "{real}".format(real=self.real) if self.real != 0 else ""

# Want to have "a + bi", "a", "bi"

# Want to avoid "+ bi" or "a + "

if self.real != 0 and self.img < 0:

string += " - " # img will already have -

elif self.real != 0 and self.img > 0:

string += " + "

string += "{img}i".format(img=abs(self.img)) if self.img != 0 else ""

return string

def __add__(self, other: 'Complex') -> 'Complex':

return Complex(self.real + other.real, self.img + other.img)

def __sub__(self, other: 'Complex') -> 'Complex':

return Complex(self.real - other.real, self.img - other.img)

def __matmul__(self, other: 'Complex') -> 'Complex':

# (ac - bd)

real = self.real * other.real - self.img * other.img

# (ad + bc)

img = self.real * other.img + self.img * other.real

return Complex(real, img)

def __mul__(self, other):

return Complex(self.real * other, self.img * other)

def __rmul__(self, other):

return self.__mul__(other)

问题是,我找不到一种定义以下内容的方法:

Complex*Complex(类实例的左乘法)

float*Complex(右标量乘法,但也可以使用int)

这是因为当我将两个类实例相乘时,它仍然调用

__mul__

__matmul__

. 我想

__马特姆__

@

操作员。我怎样才能在不使用其他操作员的情况下完成所有这些工作(

) ? 我想用标准

*

操作员。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值