python两个小于号什么意思_Python:使用星号(*)将两个对象“相乘”是什么意思?...

该*只是意味着“multiply”。

但是,两个对象相乘意味着什么取决于那些对象的类型来决定。

对于所有内置和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:>>> class C: pass

>>> C * 2

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

如果你(或第三方库作者)创建新类型,可以决定乘法的含义。文档中的模拟数字类型涵盖了执行此操作的方法,但简短版本是定义__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不是a MyNumberyThing,它是a 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

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值