例如,假设我在类'Scraper()'中有一个函数'artistsearch',该函数接受参数'website','artist','keyword'和'rangenum',并且我想在脚本中多次使用此函数。不同的值。是否像下面的示例中那样简单地重新分配变量是通常的做法,还是有更多的python风格的方法来做到这一点?

# Set values for first instantiation

website="https://www.examplewebsitenumber1.com/"
artist="Da Vinci"
keyword="painting"
rangenum=7

# instantiate to object devinci
devinci=Scraper()

# run function
devinci.artistsearch(website, artist, keyword, rangenum)

# Set values for second instantiation

website="https://www.examplewebsitenumber2.com/"
artist="Gaudi"
keyword="sculpture"
rangenum=9
# instantiate to object gaudi
gaudi=Scraper()

# run function again with different values
gaudi.artistsearch(website, artist, keyword, rangenum)

and so on.........

最佳答案

重用变量是完全可以的(您只是将名称重新分配给其他名称),但是在您的情况下,您似乎需要循环和字典列表作为关键字参数传递

arglist = [
    {
        website: "https://www.examplewebsitenumber1.com/",
        artist: "Da Vinci",
        keyword: "painting",
        rangenum: 7
    }, {
        website:"https://www.examplewebsitenumber2.com/",
        artist: "Gaudi",
        keyword: "sculpture",
        rangenum: 9
    }
]

for args in arglist:
    devinci = Scraper()
    devinci.artistsearch(**args)


作为参数传递的**args与解压缩当前字典相同。例:

devinci.artistsearch(
    website="https://www.examplewebsitenumber2.com/",
    artist="Gaudi",
    keyword="sculpture",
    rangenum=9
)


我当然不确定artistsearch中的参数名称,但是您明白了(最糟糕的是,创建一个列表列表,然后将参数作为位置传递,在这种情况下为artistsearch(*args)

10-08 16:49