有人可以解释一下这块微型 python 发生了什么吗

Can someone explain what is happening with this piece of micro python

刚开始玩 BBC micro:bit。其中一个例子有这行代码

flash = [Image().invert()*(i/9) for i in range(9, -1, -1)]

它生成一组图像。为了弄清楚发生了什么,我写了这段代码

class Image:
    def __init__(self,*args):
        print ("init")
        for a in args:
            print (a)

    def invert(self, *args):
        print ("invert")
        for a in args:
            print (a)


flash = [Image().invert()*(i/9) for i in range(9, -1, -1)]

print ( flash )

产生

python3 test.py 
init
invert
Traceback (most recent call last):
  File "test.py", line 14, in <module>
    flash = [Image().invert()*(i/9) for i in range(9, -1, -1)]
  File "test.py", line 14, in <listcomp>
    flash = [Image().invert()*(i/9) for i in range(9, -1, -1)]
TypeError: unsupported operand type(s) for *: 'NoneType' and 'float'

谢谢

你的函数 invert 没有返回任何东西,所以当你尝试将它相乘时,你 None*float 得到了你描述的答案。

invert()你需要传递一些int值和return任何int值。在您的代码中,您的 invert()[=19 中没有 returning 任何 intfloat 值=] 函数。试试这个

class Image:
    def __init__(self,*args):
        print ("init")
        for a in args:
            print (a)

    def invert(self, *args):
        print ("invert")
        for a in args:
            return a
flash = [Image().invert(1,)*(i/9) for i in range(9, -1, -1)]
print (flash)

这会起作用

刚刚发现图像有一个 * 运算符,即它不是解包运算符,这让我感到困惑。

感谢您的回复