Pylint规则:如何解决未定义的变量?

时间:2015-10-20 01:10:27

标签: python-2.7 pylint

我从pylint规则中得到一些消息:

from scrapy.spiders import Spider
class MySpider(Spider):           #Undefined variable "Spider"
    name = "get"
    start_urls = [""]

    def __init__(self,**kwargs):
        self.page_num = 1         #Undefined variable "self"
        super(MySpider, self).__init__()

    def parse(self, response):
        sel = Selector(response)                #Undefined variable "response"
        sites = sel.css("")                     #Undefined variable "sel"
        category_projects_list = []
        for site in sites:                      #Undefined variable "site"
            project_count = site.css("") 
            category_name = site.css("").extract()
            category_projects = {}
            category_projects['project_count'] = project_count[0]  #Undefined variable "category_projects"  #Undefined variable "project_count"  

我有点困惑如何编辑代码
这意味着我在使用之前已经声明了它?

Spider=None
self=None
response= None
sel=None
site=None
...

但是Spider来自from scrapy.spiders import Spider我应该如何声明它?

我认为category_projects = {}声明了变量

但下一行说Undefined variable "category_projects"

我想知道如何编辑代码以符合规则? 这样我就可以参考修改其他代码

2 个答案:

答案 0 :(得分:1)

似乎pytest中有一个错误我用tox运行了以下测试:

[tox]
skipsdist = True
envlist = py{27,34}-pylint{141,142,143,144,145}

[testenv]
whitelist_externals = pylint
deps =
  pylint141: pylint==1.4.1
  pylint142: pylint==1.4.2
  pylint143: pylint==1.4.3
  pylint144: pylint==1.4.4
  pylint145: pylint==1.4.5
commands = pylint -r n test.py

在以下文件

"""Custom exceptions"""

class MyException(Exception):
    """My custom exception"""

    def __init__(self, message):
        super(MyException, self).__init__(message)

我获得了以下结果:

ERROR:   py27-pylint141: commands failed
ERROR:   py27-pylint142: commands failed
ERROR:   py27-pylint143: commands failed
ERROR:   py27-pylint144: commands failed
  py27-pylint145: commands succeeded
ERROR:   py34-pylint141: commands failed
ERROR:   py34-pylint142: commands failed
ERROR:   py34-pylint143: commands failed
ERROR:   py34-pylint144: commands failed
  py34-pylint145: commands succeeded

出现这些错误:

************* Module test
E:  7,27: Undefined variable 'self' (undefined-variable)
E:  7,42: Undefined variable 'message' (undefined-variable)

假设这样,最好的方法是至少转到1.4版本的pylint。

答案 1 :(得分:-2)

您不必在Python中声明变量。你的班级定义是错误的。在Python中,您不需要参数和括号。 Class Definition Syntax

class MySpider: 
    #your code here