簡體   English   中英

Python:如何從導入的模塊調用類方法? “自我”論點問題

[英]Python: How to call class method from imported module? “Self” argument issue

我有2個檔案。 我知道如何調用函數,但是無法理解如何正確地從以“ self”作為第一個參數的導入模塊中調用方法。

我收到此錯誤:

TypeError:prepare()缺少1個必需的位置參數:“ url”

cinemas.py    

import requests
from lxml.html import fromstring

class cinemas_info():

    def __init__(self, url):
        self.basic_cinemas_info(url)

    def prepare(self, url):


        url = requests.get(url)
        tree = fromstring(url.text)
        tree.make_links_absolute(url.url)
        return tree

    def basic_cinemas_info(self, url):


        tree = self.prepare(url)

        for city in tree.xpath(".//div[@class='city-caption']"):
            city1 = city.xpath("text()")[0]
            for cinema in city.xpath("following-sibling::*[1]/li/a"):
                name1 = cinema.xpath("text()")[0]
                detailed_url = cinema.xpath("@href")[0]
                print (city1.strip(), name1.strip(), ':')
                self.detailed_cinemas_info(detailed_url)
                self.detailed_cinemas_films(detailed_url)

    def detailed_cinemas_info(self, url):


        tree = self.prepare(url)

        for street in tree.xpath(".//div[@class='address']"):
            street1 = street.xpath("text()")[0]
            for phone in tree.xpath(".//div[@class='phone']"):
                phone1 = phone.xpath("text()")[0]
                for website in tree.xpath(".//div[@class='website']/a"):
                    website1 = website.xpath("@href")[0]
                    print ('\t', street1.strip(), phone1.strip(), website1.strip())

    def detailed_cinemas_films(self, url):


        showtimes_tab_url = '/showtimes/#!=&cinema-section=%2Fshowtimes%2F'
        tree = self.prepare(url + showtimes_tab_url)

        for film in tree.xpath('//div[@class="content"]'):
            film_name = film.xpath('.//a[@class="navi"]/text()')[0]
            for dates in film.xpath('.//li[contains(@class,"showtimes-day sdt")]'):
                film_dates = dates.xpath('.//div[@class="date"]/text()')[0]
                for times in dates.xpath('.//ul[@class="showtimes-day-block"]/li'):
                    film_times = times.xpath('a/text()')

                    if len(film_times) == 0:
                        film_times = None

                    is_3d = times.find('span')
                    if film_times is not None:
                        if is_3d is not None:
                            print(film_dates, film_name, film_times[0], '3D')
                        else:
                            print(film_dates, film_name, film_times[0])

if __name__ == "__main__":
    cinemas_info('http://vkino.com.ua/cinema/#!=')

#films.py

import requests
from cinemas import cinemas_info

def films_list():
    url = 'http://vkino.com.ua/afisha#!='
    tree = cinemas_info.prepare(url) #  <<<----Here is my call

    for films in tree.xpath('//*[@id="content"]/div/div[1]/ul[2]/li'):
        film_name = films.xpath('.//div[@class="title"]/a/text()')[0]
        film_url = films.xpath('.//div[@class="title"]/a/@href')[0]
        print(film_name, film_url)

if __name__ == "__main__":
    films_list()

我知道我可以將“ def prepare”移出類並刪除“ self”參數,但是我想知道,在類內部調用“ def prepare”的正確方法是什么。

from cinemas import cinemas_info

您將在此處導入類定義。 現在下一行:

cinemas_info.prepare(url)

您正在為此類定義調用prepare 您想要的是首先實例化該類,然后在該類的實例上調用prepare()

ci = cinemas_info(url)
ci.prepare(url)  # this works

編輯 :當您在實例上調用方法時,Python會自動填充self變量作為對該對象實例的引用,因此您只需要將一個參數傳遞給def prepare(self, url)

由於prepare的定義包含self ,因此可以在cinemas_info的實例上調用此方法,也可以將其實例和url傳遞給prepare()來調用此方法。

因此,您只需要創建一個cinemas_info類的實例,Python本身就會將該實例傳遞給prepare() 您只需要傳遞url

#films.py

import requests
from cinemas import cinemas_info

def films_list():
    url = 'http://vkino.com.ua/afisha#!='
    c_info = cinemas_info(url) # created an instance of cinemas_info
    tree = c_info.prepare(url) # can now call prepare() on this instance

    for films in tree.xpath('//*[@id="content"]/div/div[1]/ul[2]/li'):
        film_name = films.xpath('.//div[@class="title"]/a/text()')[0]
        film_url = films.xpath('.//div[@class="title"]/a/@href')[0]
        print(film_name, film_url)

if __name__ == "__main__":
    films_list()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM