python中用函式初始化類變數

鴨脖發表於2012-05-11

今天在寫python的時候遇到一個問題:定義了一個list型別的類變數,但是這個list需要在初始化的時候給它加很多的url進去.這樣的話我們就需要用倒函式了.結果自己剛開始這樣寫的:

class TianyaSpider(CrawlSpider):

def init_start():
        url_l = u'http://search.tianya.cn/s?tn=sty&rn=10&pn='
        url_r = u'&s=0&pid=&f=0&h=1&ma=0&q=%B8%DF%BF%BC%D6%BE%D4%B8'
        urls = []
        for i in range(0,75,1):
            tem = url_l + str(i) + url_r
            urls.append(tem)
        return urls


    name = 'tianya'
    allowed_domains = ['tianya.cn']
    start_urls = init_start()


這樣寫是成功了,但是總感覺不規範,如果你把函式的定義寫在後面那麼程式還無法識別該函式.其實我覺得這和java等是一個道理,這個方法中的程式碼是放在static區的.在第一次載入這個類的時候,這些程式碼便放了進去.這樣的函式好像是不太方便在類的外部去呼叫的.所以這樣做在python中無疑是不規範的,那麼我就想換一種表達的方式


剛開始我一直想在類定義的內部去呼叫類函式來進行該類變數的初始化,所以程式碼變成下面這個樣子:

 # -*- coding: utf-8 -*-
from scrapy.selector import HtmlXPathSelector
from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor
from scrapy.contrib.spiders import CrawlSpider, Rule
from GaoKao.items import GaokaoItem

class TianyaSpider(CrawlSpider):
    name = 'tianya'
    allowed_domains = ['tianya.cn']
    start_urls = TianyaSpider.init_start()

    count = 0
    
    
    def parse(self, response):
        hxs = HtmlXPathSelector(response)
        self.count = self.count + 1
        #title = hxs.select("//div[@id='post-title'][@class='fn-clear']/h1[@id='hTitle']//*/text()").extract()
        title = hxs.select('//title/text()').extract()
        item = GaokaoItem()
        item['title'] = title[0]
        
        yield item
    @classmethod
    def init_start(cls):
        url_l = u'http://search.tianya.cn/s?tn=sty&rn=10&pn='
        url_r = u'&s=0&pid=&f=0&h=1&ma=0&q=%B8%DF%BF%BC%D6%BE%D4%B8'
        urls = []
        for i in range(0,75,1):
            tem = url_l + str(i) + url_r
            urls.append(tem)
        return urls
        
    
            
   
但是報錯說TinayaSpider沒有定義,你了個妹的,估計是當成物件了,接著我又這樣做:

 # -*- coding: utf-8 -*-
from scrapy.selector import HtmlXPathSelector
from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor
from scrapy.contrib.spiders import CrawlSpider, Rule
from GaoKao.items import GaokaoItem

class TianyaSpider(CrawlSpider):
    @classmethod
    def init_start(cls):
        url_l = u'http://search.tianya.cn/s?tn=sty&rn=10&pn='
        url_r = u'&s=0&pid=&f=0&h=1&ma=0&q=%B8%DF%BF%BC%D6%BE%D4%B8'
        urls = []
        for i in range(0,75,1):
            tem = url_l + str(i) + url_r
            urls.append(tem)
        return urls
    name = 'tianya'
    allowed_domains = ['tianya.cn']
    start_urls = init_start()

    count = 0
    
    
    def parse(self, response):
        hxs = HtmlXPathSelector(response)
        self.count = self.count + 1
        #title = hxs.select("//div[@id='post-title'][@class='fn-clear']/h1[@id='hTitle']//*/text()").extract()
        title = hxs.select('//title/text()').extract()
        item = GaokaoItem()
        item['title'] = title[0]
        
        yield item
    
        
    
            
   
但是還是報錯說不能呼叫該類方法.

至今不知道在這裡怎麼去呼叫類方法來進行初始化.

但是我一想,我可以通過例項方法來改變.所以我把程式碼的結構一改,換成如下:

 # -*- coding: utf-8 -*-
from scrapy.selector import HtmlXPathSelector
from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor
from scrapy.contrib.spiders import CrawlSpider, Rule
from GaoKao.items import GaokaoItem

class TianyaSpider(CrawlSpider):
    def init_start(cls):
        url_l = u'http://search.tianya.cn/s?tn=sty&rn=10&pn='
        url_r = u'&s=0&pid=&f=0&h=1&ma=0&q=%B8%DF%BF%BC%D6%BE%D4%B8'
        urls = []
        for i in range(0,75,1):
            tem = url_l + str(i) + url_r
            urls.append(tem)
        return urls
    name = 'tianya'
    allowed_domains = ['tianya.cn']
    start_urls = []
    count = 0
    
    def __init__(self):
        CrawlSpider.__init__(self)
        TianyaSpider.start_urls = self.init_start()
    
    def parse(self, response):
        hxs = HtmlXPathSelector(response)
        self.count = self.count + 1
        #title = hxs.select("//div[@id='post-title'][@class='fn-clear']/h1[@id='hTitle']//*/text()").extract()
        title = hxs.select('//title/text()').extract()
        item = GaokaoItem()
        item['title'] = title[0]
        
        yield item
        
    def init_start(self):
        url_l = u'http://search.tianya.cn/s?tn=sty&rn=10&pn='
        url_r = u'&s=0&pid=&f=0&h=1&ma=0&q=%B8%DF%BF%BC%D6%BE%D4%B8'
        urls = []
        for i in range(0,75,1):
            tem = url_l + str(i) + url_r
            urls.append(tem)
        return urls
        
    
            
   
這樣便成功了.不知道為什麼這裡就識別除了tinayaspider了


相關文章