[英]Python function recursion within a class
我做了下面的课。
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
我不确定该如何将函数添加到类中,因为它需要递归。
将results = dict_value_finder(value, field, partial_match)
更改为此:
results = self.dict_value_finder(value, field, partial_match)
和more_results = dict_value_finder(item, field,partial_match)
可以:
more_results = self.dict_value_finder(item, field,partial_match)
为了访问类实例的属性,我们应该使用self
。
解决评论中的问题:
def dict_value_finder(self, field, partial_match=False, search=None):
fields_found = []
search = search or self.message
for key, value in search.items():
if field in key if partial_match else field == key:
fields_found.append(value)
print(key, value)
elif isinstance(value, dict):
results = self.dict_value_finder(field, partial_match, value)
fields_found.extend(results)
elif isinstance(value, list):
for item in value:
if isinstance(item, dict):
more_results = self.dict_value_finder(field,partial_match, item)
fields_found.extend(more_results)
return fields_found
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.