【发布时间】:2019-05-06 22:31:10
【问题描述】:
我做了下面的课程。
class Message:
def __init__(self, message):
self.message = message
self.__dict__.update(message)
def dict_value_finder(self, field, partial_match=False):
"""It Takes a dict with nested lists and dicts,
and searches all dicts for a key of the field
provided and return the value(s) as a list.
set partial_match = True to get partial matches.
"""
fields_found = []
for key, value in self.message.items():
if field in key if partial_match else field == key:
fields_found.append(value)
print(key, value)
elif isinstance(value, dict):
results = dict_value_finder(value, field, partial_match)
fields_found.extend(results)
elif isinstance(value, list):
for item in value:
if isinstance(item, dict):
more_results = dict_value_finder(item, field,
partial_match)
fields_found.extend(more_results)
return fields_found
函数 dict_value_finder 可以在类之外工作,如下所示:
def dict_value_finder(search_dict, field, partial_match=False):
"""Takes a dict with nested lists and dicts,
and searches all dicts for a key of the field
provided and return the value(s) as a list.
set partial_match = True to get partial matches.
"""
fields_found = []
for key, value in search_dict.items():
if field in key if partial_match else field == key:
fields_found.append(value)
print(key, value)
elif isinstance(value, dict):
results = dict_value_finder(value, field, partial_match)
fields_found.extend(results)
elif isinstance(value, list):
for item in value:
if isinstance(item, dict):
more_results = dict_value_finder(item, field,
partial_match)
fields_found.extend(more_results)
return fields_found
但是当我把它放在类中时,我得到了错误:
File "<ipython-input-42-76ab838299bc>", line 23, in dict_value_finder
results = dict_value_finder(value, field, partial_match)
NameError: name 'dict_value_finder' is not defined
我不确定如何将此函数添加到需要递归的类中。
【问题讨论】:
-
您在引用
message时使用了self,但在引用dict_value_finder时没有使用。为什么?
标签: python function class recursion methods