0

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?

2
  • 3
    def scrape(brand): bot = Bot(login, password, brand=brand, ...); bot.log_in(); ...…? Commented Nov 10, 2021 at 10:32
  • 1
    removing the unrelated tags – the fact that this is about a bot doesn't relate to the question. (also, fixed your classes indentation – Python is sensitive to that) Commented Nov 10, 2021 at 10:33

2 Answers 2

3

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()
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.