【问题标题】:How to combine multiple similar functions inside a class into, referencing to attributes inside the class如何将一个类内部的多个相似函数组合成,引用类内部的属性
【发布时间】:2022-12-20 03:30:25
【问题描述】:

在下面的代码中,您会看到多个函数为此类的另一个属性做几乎相同的事情

class IDManager():
    def __init__(self):

        self.inputIDs = []
        self.outputIDs = []
        self.operatorIDs = []
        self.dataManagerIDs = []
        self.timeManagerIDs = []

    def setIDS(self, min, max):
        self.inputIDs = list(range(min, max))

    def setOutputIDS(self, min, max):
        self.outputIDs = list(range(min, max))

    def setOperatorIDS(self, min, max):
        self.operatorIDs = list(range(min, max))

    def setDataManagerIDS(self, min, max):
        self.dataManagerIDs = list(range(min, max))

    def setTimeManagerIDS(self, min, max):
        self.timeManagerIDs = list(range(min, max))

这对我来说看起来很乱。这让我想知道,在向函数添加类型变量时,是否可以将其简化为一个函数。下面的示例显然不起作用,因为 self.type 中的类型现在正在寻找不同的属性。

def setIDS(self, type, min, max):
            self.type = list(range(min, max))

【问题讨论】:

    标签: python function class variables simplify


    【解决方案1】:

    直接设置属性怎么样:

    class IDManager():
        def __init__(self):
    
            self.inputIDs = []
            self.outputIDs = []
            self.operatorIDs = []
            self.dataManagerIDs = []
            self.timeManagerIDs = []
    
        def set_XXX_ID(self, min, max, XXX_attr):
            setattr(self, XXX_attr, list(range(min, max)))
    
    

    然后您可以使用属性名称调用它,例如:

    myIDManager = IDManager()
    myIDManager.set_XXX_ID(0, 10, 'dataManagerIDs')
    

    【讨论】:

      猜你喜欢
      • 2017-12-18
      • 2021-07-27
      • 2018-08-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-16
      • 1970-01-01
      • 2021-11-27
      相关资源
      最近更新 更多