函数不可变参数重写

2024-09-27 20:20:31 发布

您现在位置:Python中文网/ 问答频道 /正文

函数参数使用可变类型 -&燃气轮机;错误)参数有多个值

Jupyter票据

https://docs.python.org/ko/3/tutorial/controlflow.html

def parrot(voltage, state='a stiff', action='voom', type='Norwegian Blue'):
    print("-- This parrot wouldn't", action, end=' ')
    print("if you put", voltage, "volts through it.")
    print("-- Lovely plumage, the", type)
    print("-- It's", state, "!")
parrot(110, voltage=220)
def parrot(voltage, state='a stiff', action='voom', type='Norwegian Blue'):
    print("-- This parrot wouldn't", action, end=' ')
    print("if you put", voltage, "volts through it.")
    print("-- Lovely plumage, the", type)
    print("-- It's", state, "!")

为什么参数变量可以被用户可变类型覆盖

parrot({1,2,}, voltage={})

TypeError回溯(最近一次调用) 在 ----&燃气轮机;1只鹦鹉({1,2,},电压={}) 2 # ???

TypeError:parrot()为参数“voltage”获取了多个值


Tags: 类型参数deftypeactionbluethisparrot
1条回答
网友
1楼 · 发布于 2024-09-27 20:20:31

得到该错误的原因是在函数定义中,第一个参数是voltage。调用parrot时,在这个call语句中传递的第一个参数将被赋予voltage

现在,在parrot(110,voltage=220)中,您将给voltage2个不同的值,110和220。这自然会产生一个错误。同样,出于同样的原因,即使对于parrot({1,2,}, voltage={}),您也会得到同样的错误

可以通过删除函数调用中的任一参数来修复此问题

相关问题 更多 >

    热门问题