简体   繁体   中英

Python:how to call def in class

I practice Scrapy and want to ask a question:

I know how to use def printTW when it out of the class
How can I calling it when I write it inside class ?
My code is here: Please teach me

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) 

To call instance method, you need to qualify the method with self .

self.printTW(movie_description) 

And the method should have a self as the first parameter:

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

Because the printTW does not use any instance attribute, you can define the method as static method (or you can define it as function, not a method).

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

Declare the function as global within the method you wish to call it, like so:

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) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM