Python - 使用两个相互依赖的类和一个 for 循环

时间:2021-03-25 11:59:54

标签: python loops class

我的问题基本上如下:我有两个类:

  • 第 1 类在循环中执行某些操作(网页抓取)
  • 第 2 类具有不同的功能,可以使某些人在此循环和将来的类似循环中必须执行的操作自动化。

这个想法是尽可能地抽象出第 1 类。

示例:类 2 有一个函数,在某些迭代后“像人类一样暂停”

(摘录)

    def pause_like_human(self):
    ''' Pausing long every x-th iteration or else short '''
    # every 20th iteration - wait for 5-10 minutes before continuing
    if self.index_no % self.index_counter == 0:
        timestamp = time.localtime()
        return print("Let's wait " + str(self.waiting_time_long) + " seconds! The time is: "\
              + str(timestamp.tm_hour) + ":" + str(timestamp.tm_min) + ":"\
                  + str(timestamp.tm_sec)), time.sleep(self.waiting_time_long)
    else:
        return print("Let's continue! ... after " + str(self.waiting_time_short) + " seconds..."), time.sleep(self.waiting_time_short)

现在我的问题是我需要从我在第 2 类中使用的循环中导入“index_no”......一遍又一遍。

(index_no 在这个循环中:)

        for index_no, city in enumerate(self.df['column'][len(self.dic)-1:], start = len(self.dic)-1):

对我来说,这听起来效率很低 - 有人有更好的主意吗?

1 个答案:

答案 0 :(得分:0)

所以我的答案似乎是我更简单地抽象代码。这会将我的“复杂”循环变成一个非常简单的循环,并将我的两个类变成一个类。 第 1 类变成了一个带有链接的更长的列表,但实际上已经做好了充分的准备。 类 2 变成了一个更通用的类,已经继承了前类 1 的大部分功能。

如果有人提出一般帮助或提示,我不介意让这篇文章保持开放状态...