Python:如何在课堂上调用def

时间:2014-07-23 04:20:24

标签: python python-2.7 scrapy

我练习Scrapy并且想问一个问题:

我知道如何在课外使用def printTW 我在课堂上写的时候如何调用呢? 我的代码在这里: 请教我

from scrapy.spider import Spider
from scrapy.selector import Selector
from yahoo.items import YahooItem

def printTW(original_line):
    for words in original_line:
        print words.encode('utf-8')     

class MySpider(Spider):   
    name = "yahoogo"
    start_urls = ["https://tw.movies.yahoo.com/chart.html"]  

    #Don't know how to calling this
    #def printTW(original_line):
    #    for words in original_line:
    #        print words.encode('utf-8')     

    def parse(self, response):
        for sel in response.xpath("//tr"):
            movie_description = sel.xpath("td[@class='c3']/a/text()").extract()
            printTW(movie_description) 

2 个答案:

答案 0 :(得分:2)

要调用实例方法,您需要使用self限定方法。

self.printTW(movie_description) 

该方法应该有self作为第一个参数:

def printTW(self, original_line):
    for words in original_line:
        print words.encode('utf-8')     

因为printTW不使用任何实例属性,所以可以将方法定义为静态方法(或者可以将其定义为函数,而不是方法)。

@staticmethod
def printTW(original_line):
    for words in original_line:
        print words.encode('utf-8')     

答案 1 :(得分:0)

将函数声明为您希望调用它的方法中的全局函数,如下所示:

def parse(self, response):
    global printTW
    for sel in response.xpath("//tr"):
        movie_description = sel.xpath("td[@class='c3']/a/text()").extract()
        printTW(movie_description)