如何将返回值赋给_init__值

2024-09-30 16:42:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试将getItemgetBuyingType的返回值分配给函数中__init__方法中的self变量。我该怎么做?如果不可能,是否有其他方法将这两个函数的输出指定为Ebay Scraper类的一部分?项目应分配给self.itembuying_type分配给self.buying_type

class EbayScraper(object):
    def __init__(self):
        self.base_url = "https://www.ebay.com/sch/i.html?_nkw="
        self.item =
        self.buying_type =
        self.url_seperator = "&_sop=12&rt=nc&LH_"
        self.url_seperator2 = "&_pgn="
        self.page_num = "1"
        self.currentPage = 1

    def getItem(self):
        item = input("Item: ")
        return item

    def getBuyingType(self):
        buying_type = input("Please specify a buying type (Auction or Buy It Now): ")
        buying_type = buying_type.lower()

        if buying_type == "auction":
            return buying_type + "=1"
        elif buying_type == "buy it now":
            return buying_type + "=1"
        else:
            print("Invalid buying type specified.")
            self.getBuyingType()

Tags: 方法函数selfurlinputreturninitdef
2条回答

您可以在__init__方法中调用函数

def __init__(self):
    ...
    self.item = self.getItem()

正确的方法是将参数传递给__init__以初始化值。如果要提供用于提供这些参数的交互式方法,请定义类方法

class EbayScraper(object):
    def __init__(self, item, buying_type):
        self.base_url = "https://www.ebay.com/sch/i.html?_nkw="
        self.item = item
        self.buying_type = buying_type
        self.url_seperator = "&_sop=12&rt=nc&LH_"
        self.url_seperator2 = "&_pgn="
        self.page_num = "1"
        self.currentPage = 1

    @classmethod
    def prompt_user(cls):
        item = input("Item")
        while True:
            buying_type = input("Please specify a buying type...").lower()
            if buying_type in ('auction', 'buy it now'):
                break
            print("Invalid buying type specified")

        return cls(item, buying_type + "=1")



e = EbayScraper.prompt_user()

相关问题 更多 >