实例属性attribute_name在__init__外部定义 [英] Instance attribute attribute_name defined outside __init__
问题描述
我通过调用多个函数来拆分类构造函数,如下所示:
I split up my class constructor by letting it call multiple functions, like this:
class Wizard:
def __init__(self, argv):
self.parse_arguments(argv)
self.wave_wand() # declaration omitted
def parse_arguments(self, argv):
if self.has_correct_argument_count(argv):
self.name = argv[0]
self.magic_ability = argv[1]
else:
raise InvalidArgumentsException() # declaration omitted
# ... irrelevant functions omitted
我的解释器很高兴地运行我的代码,Pylint有一个投诉:
While my interpreter happily runs my code, Pylint has a complaint:
实例属性attribute_name定义在__init之外__
粗略的Google搜索目前是无效的。保持 __ init __
中的所有构造函数逻辑似乎无组织,并且关闭Pylint警告也似乎是hack-ish。
A cursory Google search is currently fruitless. Keeping all constructor logic in __init__
seems unorganized, and turning off the Pylint warning also seems hack-ish.
推荐答案
这个讯息背后的想法是:为了可读性。我们希望通过读取它的 __ init __
方法来查找实例可能具有的所有属性。
The idea behind this message is for the sake of readability. We expect to find all the attributes an instance may have by reading its __init__
method.
分割初始化为其他方法。在这种情况下,您可以在 __ init __
中简单地将属性分配给无
子初始化方法。
You may still want to split initialization into other methods though. In such case, you can simply assign attributes to None
(with a bit of documentation) in the __init__
then call the sub-initialization methods.
这篇关于实例属性attribute_name在__init__外部定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!