[英]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.