【问题标题】:Python:how to call def in classPython:如何在课堂上调用 def
【发布时间】:2014-09-14 02:59:38
【问题描述】:

我在练习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) 

【问题讨论】:

    标签: python python-2.7 scrapy


    【解决方案1】:

    要调用实例方法,您需要使用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')     
    

    【讨论】:

      【解决方案2】:

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

      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) 
      

      【讨论】:

      • global printTW 不是必需的。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-01-08
      • 2019-07-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-19
      • 2019-03-26
      相关资源
      最近更新 更多