我在人工智能:一种现代方法代码存储库中遇到了以下代码,这是我以前从未见过的:
def __init__(self, state, parent=None, action=None, path_cost=0):
"Create a search tree Node, derived from a parent by an action."
update(self, state=state, parent=parent, action=action,
path_cost=path_cost, depth=0)
if parent:
self.depth = parent.depth + 1他们似乎在使用update函数重新定义构造函数的参数,以允许其他参数。我在代码中到处查找,找不到一个名为update的自定义函数。这在蟒蛇里允许吗?我在网上找不到。
发布于 2015-06-03 21:55:17
这不是Python的内建函数之一,因为它不是在本地定义的,也不是在以下内容中列出的:
import math, random, sys, time, bisect, string(呜!)它一定来自于文件中唯一的其他import:
from utils import *(这就是为什么风格指南说“应该避免通配符导入,因为它们使名称空间中的名称不清楚”.)。
在那个档案中我们发现:
def update(x, **entries):
"""Update a dict; or an object with slots; according to entries.
>>> update({'a': 1}, a=10, b=20)
{'a': 10, 'b': 20}
>>> update(Struct(a=1), a=10, b=20)
Struct(a=10, b=20)
"""
if isinstance(x, dict):
x.update(entries)
else:
x.__dict__.update(entries)
return x这个函数的使用稍微简化了原来的样子:
def __init__(self, state, parent=None, action=None, path_cost=0):
"Create a search tree Node, derived from a parent by an action."
self.state = state
self.parent = parent
self.action = action
self.path_cost = path_cost
self.depth = 0
if parent:
self.depth = parent.depth + 1https://stackoverflow.com/questions/30631351
复制相似问题