Python:如何在类中调用方法

2 投票
2 回答
1624 浏览
提问于 2025-04-18 14:23

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

在你想要调用这个函数的方法里,把它声明为全局的,像这样:

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) 
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')     

撰写回答