2022年 11月 3日

python中星号_Python中的星号符号

Python中的星号实际上只是标准的乘法运算符*。它映射到它所操作的对象的^{}方法,因此可以重载以具有自定义含义。这与if或print无关。在

在字符串(str和unicode)的情况下,它被重载/重写以表示字符串的重复,这样”foo” * 5的计算结果为”foofoofoofoofoo”。在>>> ‘foo’ * 5 # and the other way around 5 * “foo” also works

‘foofoofoofoofoo’

而”Fizz” * (i % 3 == 0)只是一个“聪明”的简写:

^{pr2}$

这是因为表达式i % 3 == 0的计算结果是布尔值,而布尔值是Python中整数的一个子类型,因此True == 1和{},因此如果将一个字符串与布尔值“相乘”,则将得到相同的字符串或空字符串。在

注意:我还想指出,根据我的经验/理解,这种类型的编程风格在Python中是不受鼓励的,它使代码的可读性降低(对新手和老用户都是如此),而且速度也不快(事实上,很可能更慢;请参阅http://pastebin.com/Q92j8qga以获取快速基准测试(但有趣的是,不在PyPy中:http://pastebin.com/sJtZ6uDm)。在

并且*也适用于list和{}的实例:>>> [1, 2, 3] * 3

[1, 2, 3, 1, 2, 3, 1, 2, 3]

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

(1, 2, 3, 1, 2, 3, 1, 2, 3)class Foo(object):

def __mul__(self, other):

return “called %r with %r” % (self, other)

print Foo() * “hello” # same as Foo().__mul__(“hello”)

输出:called <__main__.foo object at> with ‘hello’

将*映射到__mul__的情况也适用于诸如int、float等“原始”类型,因此3 * 4等同于{}(其他运算符也是如此)。实际上,您甚至可以子类int,并为*提供自定义行为:class MyTrickyInt(int):

def __mul__(self, other):

return int.__mul__(self, other) – 1

def __add__(self, other):

return int.__add__(self, other) * -1

print MyTrickInt(3) * 4 # prints 11

print MyTrickyInt(3) + 2 # prints -5

…但请不要这样做:)(事实上,保持对具体类型的子类化完全没有坏处!)在