Python函数参数顺序的机制

时间:2019-12-15 03:37:55

标签: python python-3.x function arguments

以下是摘自《 Python Crash course》一书中一个简单的python示例的摘录 我的问题与fire_bullet接受的参数有关。我想知道为什么尽管在括号中明确指定了“子弹”,但“第4行:len(子弹)”却坚持要采用“第1行:def fire_bullet(ai_settings,screen,ship,bullets)”中的最后一个参数,所以如果我在这里没有将项目符号作为最后一个参数,那么代码将不起作用。例如,如果我将“子弹”的位置替换为“船”,则“第4行:如果len(bullets)

我知道一般规则,即位置参数根据定义需要特定的顺序,但是在下面的示例中,参数被清楚地清楚地说明,就像它们被命名为参数一样,此外,如果确实需要'line 1:def fire_bullet'那么它的论点在特定位置,那么为什么第一个“第4行:len(bullets)坚持读最后一个论点”在第1行:子弹”

1. def fire_bullet(ai_settings, screen, ship, bullets):
2.    """Fire a bullet if limit no reached yet."""
3.   (# omitted) Create a new bullet and add it to the bullets group
4.    if len(bullets) < ai_settings.bullets_allowed:
5.            new_bullet = Bullet(ai_settings, screen, ship)
6.            bullets.add(new_bullet)

2 个答案:

答案 0 :(得分:0)

该问题与参数的命名无关,与实际上如何调用函数fire_bullet无关。如果您切换参数,您发布的代码片段将可以正常运行,但是在程序的其他位置,函数fire_bullet的调用是通过列表作为最终参数。如果要更改参数出现的顺序,还应确保fire_bullet函数的每个调用都以新的顺序设置参数。

答案 1 :(得分:0)

换句话说,这是错误的地方(经典示例foobar()):

def foobar(a, b):
    print(b)

foobar(1, 2) # this will print 2
foobar(2, 1) # this will print 1
# As you can see, order matters not
# only when you write the function, 
# but when you call it as well

在其他地方的程序中,调用fire_bullet函数时,顺序混乱。