该*只是意味着“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