Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/311.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/oop/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python AttributeError:“Spider”对象没有属性“table”_Python_Oop_Scrapy - Fatal编程技术网

Python AttributeError:“Spider”对象没有属性“table”

Python AttributeError:“Spider”对象没有属性“table”,python,oop,scrapy,Python,Oop,Scrapy,我和scrapy一起工作。我有一只蜘蛛,它的开头是: class For_Spider(Spider): name = "for" # table = 'hello' # creating dummy attribute. will be overwritten def start_requests(self): self.table = self.dc # dc is passed in 我有以下管道: class DynamicSQLlitePi

我和scrapy一起工作。我有一只蜘蛛,它的开头是:

class For_Spider(Spider):

    name = "for"
#    table = 'hello' # creating dummy attribute. will be overwritten

    def start_requests(self):

        self.table = self.dc # dc is passed in
我有以下管道:

class DynamicSQLlitePipeline(object):

    @classmethod
    def from_crawler(cls, crawler):
        # Here, you get whatever value was passed through the "table" parameter
        table = getattr(crawler.spider, "table")
        return cls(table)

    def __init__(self,table):
        try:
            db_path = "sqlite:///"+settings.SETTINGS_PATH+"\\data.db"
            db = dataset.connect(db_path)
            table_name = table[0:3]  # FIRST 3 LETTERS
            self.my_table = db[table_name]
当我启动蜘蛛时:

scrapy crawl for -a dc=input_string -a records=1
我得到:

AttributeError: 'For_Spider' object has no attribute 'table'
如果我取消注释“table”,程序将启动。我不明白为什么“table”有效,而self.table无效。有人能解释一下吗?

表可以工作,因为它是For_Spider的类属性,self.table正好在函数范围内。self表示实例本身,因此在这种情况下,在函数内部不需要使用它,除非您在_init__;中定义它。 如果尝试在函数范围外定义self.table,则会出现错误

另外,尝试在这两个类上使用_dict__;来查看它们的属性和函数 对表进行了注释:

{'doc':无,'start_requests':,'name':'for','module':'builtins'}

如您所见,没有表属性

对于未注释的表:

{'doc':无,'start_requests':,'table':'hello','name':'for','module':'builtins'}


我希望这是清楚的:>

谢谢你看这个。我想我把类属性和实例属性搞混了。我认为它们本质上是一样的。另外,更实际地说,我想从命令行传递一个“table”参数,以动态地设置一个管道可以访问的table变量。