python 中是否隐含 'other' 是列表中的另一个对象?参数从未正确引入
Is it implicit in python that 'other' is another object in a list? Parameter has never been introduced properly
我只是不明白书中的示例如何列出从未介绍过的参数 'other'。当调用该函数时,Python 自动将其理解为 Class?
看例子:
def get_neighbors(self, others, radius, angle):
"""Return the list of neighbors within the given radius and angle."""
boids = []
for other in others:
if other is self: continue
offset = other.pos - self.pos
# if not in range, skip it
if offset.mag > radius:
continue
# if not within viewing angle, skip it
if self.vel.diff_angle(offset) > angle:
continue
# otherwise add it to the list
boids.append(other)
return boids
代码中没有其他地方提到 'other'。
谢谢,只是想了解这些机制。
更新答案,回应评论
Python 对于名为 "others" 的方法参数或示例中的任何其他参数没有任何特殊行为。
很可能您正在阅读的书根本没有解释(还)如何调用该函数。也有可能这本书有误(在这种情况下,也许你应该找一本更好的书!)。
原始答案(供后人使用)
名称 other
由 for
语句声明:
for other in others:
...
来自the Python documentation for the for
statement:
The suite is then executed once for each item provided by the iterator, in the order of ascending indices. Each item in turn is assigned to the target list using the standard rules for assignments, and then the suite is executed.
这里,"the iterator" 是从列表 others
导出的,而 "the target list" 只是变量 other
。因此,在循环的每次迭代中,other
变量被分配 ("using the standard rules for assignments") 列表中的下一个值。
该方法的 DocString 应包括参数列表并解释每个参数的预期类型(我计划尽快更新此代码,并将改进文档)。
在这种情况下,others 应该是具有名为 pos 的属性(可能与 other 类型相同)的对象列表(或其他序列)。
注意名称'others'没有什么特别之处。
我只是不明白书中的示例如何列出从未介绍过的参数 'other'。当调用该函数时,Python 自动将其理解为 Class? 看例子:
def get_neighbors(self, others, radius, angle):
"""Return the list of neighbors within the given radius and angle."""
boids = []
for other in others:
if other is self: continue
offset = other.pos - self.pos
# if not in range, skip it
if offset.mag > radius:
continue
# if not within viewing angle, skip it
if self.vel.diff_angle(offset) > angle:
continue
# otherwise add it to the list
boids.append(other)
return boids
代码中没有其他地方提到 'other'。 谢谢,只是想了解这些机制。
更新答案,回应评论
Python 对于名为 "others" 的方法参数或示例中的任何其他参数没有任何特殊行为。
很可能您正在阅读的书根本没有解释(还)如何调用该函数。也有可能这本书有误(在这种情况下,也许你应该找一本更好的书!)。
原始答案(供后人使用)
名称 other
由 for
语句声明:
for other in others:
...
来自the Python documentation for the for
statement:
The suite is then executed once for each item provided by the iterator, in the order of ascending indices. Each item in turn is assigned to the target list using the standard rules for assignments, and then the suite is executed.
这里,"the iterator" 是从列表 others
导出的,而 "the target list" 只是变量 other
。因此,在循环的每次迭代中,other
变量被分配 ("using the standard rules for assignments") 列表中的下一个值。
该方法的 DocString 应包括参数列表并解释每个参数的预期类型(我计划尽快更新此代码,并将改进文档)。
在这种情况下,others 应该是具有名为 pos 的属性(可能与 other 类型相同)的对象列表(或其他序列)。
注意名称'others'没有什么特别之处。