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
While my interpreter happily runs my code, Pylint has a complaint:
当我的口译员愉快地运行我的代码时,Pylint抱怨:
Instance attribute attribute_name defined outside __init__
在__init__外定义的实例属性attribute_name
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.
粗略的Google搜索目前毫无结果。保持__init__中的所有构造函数逻辑似乎没有组织,并且关闭Pylint警告似乎也是黑客攻击。
What is a/the Pythonic way to resolve this problem?
什么是/ Pythonic解决这个问题的方法?
2 个解决方案
#1
83
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.
您可能仍希望将初始化拆分为其他方法。在这种情况下,您可以简单地在__init__中将属性分配给None(带有一些文档),然后调用子初始化方法。
#2
19
Just return a tuple from parse_arguments()
and unpack into attributes inside __init__
as needed.
只需从parse_arguments()返回一个元组,并根据需要解压缩到__init__中的属性。
Also, I would recommend that you use Exceptions in lieu of using exit(1)
. You get tracebacks, your code is reusable, etc.
另外,我建议您使用Exceptions代替使用exit(1)。你得到追溯,你的代码是可重用的,等等。
class Wizard:
def __init__(self, argv):
self.name,self.magic_ability = self.parse_arguments(argv)
def parse_arguments(self, argv):
assert len(argv) == 2
return argv[0],argv[1]
#1
83
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.
您可能仍希望将初始化拆分为其他方法。在这种情况下,您可以简单地在__init__中将属性分配给None(带有一些文档),然后调用子初始化方法。
#2
19
Just return a tuple from parse_arguments()
and unpack into attributes inside __init__
as needed.
只需从parse_arguments()返回一个元组,并根据需要解压缩到__init__中的属性。
Also, I would recommend that you use Exceptions in lieu of using exit(1)
. You get tracebacks, your code is reusable, etc.
另外,我建议您使用Exceptions代替使用exit(1)。你得到追溯,你的代码是可重用的,等等。
class Wizard:
def __init__(self, argv):
self.name,self.magic_ability = self.parse_arguments(argv)
def parse_arguments(self, argv):
assert len(argv) == 2
return argv[0],argv[1]