python两个星号运算_Python:使用星号(*)将两个对象“相乘”在一起意味着什么?...

*运算符的意思是“乘”。在

但是,两个物体相乘意味着什么,这取决于这些物体的类型。在

对于所有的builtin和stdlib类型,如果有意义,它意味着乘法;如果没有意义的话,它是TypeError。例如:>>> 2 * 3

6

>>> (1, 2, 3) * 3

(1, 2, 3, 1, 2, 3, 1, 2, 3)

>>> "abc" * "def"

TypeError: can't multiply sequence by non-int of type 'str'

因为乘法对类对象没有意义,所以它们是TypeError的一种:

^{pr2}$

如果您(或第三方库作者)创建了一个新类型,您可以决定乘法的含义。文档中的Emulating numeric types中介绍了这种方法,但简短的说法是您定义了一个__mul__方法:class MyNumberyThing:

def __init__(self, n):

self.n = n

def __repr__(self):

return f'MyNumberyType({self.n})'

def __mul__(self, other):

if isinstance(other, MyNumberyThing):

return MyNumberyThing(self.n * other.n)

elif isinstance(other, int):

return MyNumberyThing(self.n * other)

elif isinstance(other, float):

raise TypeError("sorry, can't multiply by float because of precision issues")

else:

raise TypeError(f"sorry, don't know how to multiply by {type(other).__name__}")

请注意,这使得实例的MyNumberyThing可乘。它不会使MyNumberyThing本身可乘(MyNumberyThing不是MyNumberyThing,而是type):>>> n = MyNumberyThing(2)

>>> n * 3

MyNumberyType(6)

>>> MyNumberyThing * 3

TypeError: unsupported operand type(s) for *: 'type' and 'int'

当然,没有什么能阻止你定义一些荒谬的东西:class MySillyThing:

def __mul__(self, other):

self.storage = -other

print(f'I took your {other}')

>>> silly = MySillyThing()

>>> silly * 3

I took your 3

>>> silly.storage

-3

…当然,除了没有人会理解你的代码。(而“无名小卒”包括你,6个月后,你试图调试一些你认为你已经完成的东西…)

另外,Python实际上有两种拼写“multiply”的方法:*和{}。在

内置类型都忽略@,因此如果尝试使用它,只会得到一个TypeError。它的作用是,基本上,NumPy可以使用*进行元素乘法,使用{}进行矩阵乘法。(@运算符的魔术方法甚至被称为__matmul__)。但是当然,其他同样需要进行两种不同乘法的第三方库可以使用@作为第二种。在

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值