Ste*_*iao 136 python constructor pylint
我通过让它调用多个函数来拆分我的类构造函数,如下所示:
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
Run Code Online (Sandbox Code Playgroud)
当我的口译员愉快地运行我的代码时,Pylint抱怨:
Instance attribute attribute_name defined outside __init__
粗略的Google搜索目前毫无结果.保持所有构造函数逻辑__init__
似乎没有组织,并且关闭Pylint警告似乎也是黑客攻击.
什么是/ Pythonic解决这个问题的方法?
sth*_*ult 141
这条消息背后的想法是为了便于阅读.我们期望通过读取其__init__
方法来查找实例可能具有的所有属性.
您可能仍希望将初始化拆分为其他方法.在这种情况下,您可以简单地将属性分配给None
(使用一些文档)__init__
然后调用子初始化方法.
roi*_*ppi 29
只需根据需要从parse_arguments()
里面返回一个元组并将其解压缩到属性中__init__
.
另外,我建议你使用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]
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
64283 次 |
最近记录: |