gpt4 book ai didi

python - Pylint 说 : W0233: __init__ method from a non direct base class 'Nested' is called (non-parent-init-called)

转载 作者:行者123 更新时间:2023-11-30 21:52:20 26 4
gpt4 key购买 nike

我也是编程和Python的新手。当我尝试将数据结构包装到类中以避免 listdict 迭代时,我收到 pylint 错误消息:

W0233: __init__ method from a non direct base class 'Nested' is called (non-parent-init-called)

有没有最好的“Pythonic”方法来做到这一点?

我的json数据是这样的:

{
"template" : [
{
"folder" : "/Users/SA/Documents/GIT/rs-finance/templates",
"basetpl" : "tpl.docx",
"header" : "header_tpl.docx",
"table" : "table_tpl.docx",
"footer" : "footer_tpl.docx"
}
],
"export" : [
{
"folder" : "/Users/SA/Documents/GIT/rs-finance/export",
"name" : "result.docx"
}
]
}

当我将此数据(或其片段)加载到 dictlist 变量并尝试用此类包装它时:

class Nested ():
def __init__(self, data):
if isinstance (data, dict):
for key, value in data.items():
if isinstance(value, (float, int, str)):
setattr(self, key, value)
else:
setattr(self, key, Nested(value))
if isinstance(data, list):
for item in data:
self.__init__(item)

Pylint 不喜欢我的最后一行 😳

最佳答案

显式调用 __init__ 并没有错,但它很奇怪,这就是 Pylint 警告您的全部内容。

更好的做法是编写一个单独的递归函数来执行您想要的操作,然后从 __init__ 调用该函数。

class Nested:
def __init__(self, data):
self.recursive(data)

def recursive(self, data):
if isinstance(data, dict):
for key, value in data.items():
if isinstance(value, (float, int, str)):
setattr(self, key, value)
else:
setattr(self, key, Nested(value))
elif isinstance(data, list):
for item in data:
self.recursive(item)

关于python - Pylint 说 : W0233: __init__ method from a non direct base class 'Nested' is called (non-parent-init-called),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59912435/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com