我通过让它调用多个函数来拆分我的类构造函数,如下所示:
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解决这个问题的方法?
我最近了解到,当您特别想要执行默认视图以外的操作时,应该覆盖get方法:
class ExampleView(generic.ListView):
template_name = 'ppm/ppm.html'
def get(self, request):
manager = request.GET.get('manager', None)
if manager:
profiles_set = EmployeeProfile.objects.filter(manager=manager)
else:
profiles_set = EmployeeProfile.objects.all()
context = {
'profiles_set': profiles_set,
'title': 'Employee Profiles'
}
Run Code Online (Sandbox Code Playgroud)
这很简单,但什么时候应该使用get_queryset或get_context_data来获取?对我来说,他们似乎基本上做同样的事情,或者我只是错过了什么?我可以一起使用它们吗?这对我来说是一个混乱的主要原因.
所以重申:在什么情况下我会使用get_queryset或get_context_data,反之亦然?