在 __init__ 之外定义的实例属性 attribute_name [英] 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__外
粗略的谷歌搜索目前没有结果.将所有构造函数逻辑保留在 __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.
解决此问题的/Pythonic 方法是什么?
What is a/the Pythonic way to resolve this problem?
推荐答案
此消息背后的想法是为了可读性.我们希望通过读取它的 __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__
中简单地将属性分配给 None
(带有一些文档),然后调用子初始化方法.
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.
这篇关于在 __init__ 之外定义的实例属性 attribute_name的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!