suziex
suziex

Reputation: 72

How should I refactor this duplicate code?

So I have bot which scrapes page and I want to refactor bot which pseudocode looks like this:

bot.py:

class Bot:
    def __init__(login, password, brand, ...):
        ...
    def log_in():
        ...
    def some_methods_to_scrap():
        ...

and in main.py I have two objects of the same class and I use the same methods on them. They are almost the same besides the parameter 'brand'. In those two cases everything what bot does is the same but for different brands:

main.py

bot1=Bot(login, password, brand=A, ...)
bot1.log_in()
bot1.some_methods_to_scrap()

bot2=Bot(login, password, brand=B, ...)
bot2.log_in()
bot2.some_methods_to_scrap()

Is there any way I can remove the duplicate code in main.py?

Upvotes: 0

Views: 184

Answers (2)

Sefan
Sefan

Reputation: 709

This can be solved in one loop by looping through the brands:

bots = []
for brand in ['A','B']:
    bots.append(Bot(login, password, brand=brand, ...))
    bots[-1].log_in()
    bots[-1].some_methods_to_scrap()

Upvotes: 0

Marcus Müller
Marcus Müller

Reputation: 36337

The usual pattern here is simply the for loop:

brands = [A, B]
bots = [Bot(login, password, brand=thisbrand, …) for thisbrand in brands]

for bot in bots:
    bot.log_in()
    bot.some_method_to_scrap()

Upvotes: 3

Related Questions