python - 通过重用代码和传递成员名称来运行测试来减少行数

标签 python algorithm

我有两个来自同一类的汽车对象和一个汽车列表。

class Car:
    def __init__(self):
        pass

cars = []

car1 = Car()
car1.color = 'black'
cars.append(car1)
car2 = Car()
car2.engine = 'V8'
cars.append(car2)

我还有两个函数,用于在匹配时从 cars 中删除对象。

def rm_car_color(c):
    for car_n in cars:
        try:
            if car_n.color == c.color:
                cars.remove(car_n)
        except Exception, err:
            pass

def rm_car_engine(c):
    for car_n in cars:
        try:
            if car_n.engine == c.engine:
                cars.remove(car_n)
        except Exception, err:
            pass

如您所见,它们实际上是相同的。我想要的是能够将要检查的成员传递给函数,以便我可以删除这两个函数之一,并且只有一个在 Python 2.6.6 中处理这两个函数。这可能吗?

此代码仅用于解释。我正在处理的代码有许多这样的删除函数(总共 8 个),如果我能做到这一点,我会大大减少代码行数。

最佳答案

首先查看代码。正如您所说,这两个功能几乎相同。这两个功能的唯一区别是什么?属性(c.color vs c.engine):

if car_n.color == c.color:

对比

if car_n.engine == c.engine:

因此,您可以使用内置的 getattr 将此代码更改为功能:

def rm_car_attribute(c, attrib):
    comparison_attrib = getattr(c, attrib)
    for car_n in cars[:]:
    # Blender mentioned a good practice: not to modify the list you are iterating
    # cars[:] creates a temporary copy of cars to iterate over
        try: 
            if getattr(car_n, attrib) == comparison_attrib:
                cars.remove(car_n)
        except Exception, err:
            pass

这可以这样使用:

rm_car_attribute(c, 'engine') # same as rm_car_engine(c) from above

另一方面,我不太确定您期望的异常类型。我看到的唯一可能的错误是汽车的属性是否明确定义(即 car_instance.engine = 'V8'),但对于其中一辆车,该属性未定义(在您的汽车列表中,其中一个实例没有 engine 属性)。您可以更改 try/except 以专门捕获此错误:

def rm_car_attribute(c, attrib):
        comparison_attrib = getattr(c, attrib)
        for car_n in cars[:]:
            try: 
                if getattr(car_n, attrib) == comparison_attrib:
                    cars.remove(car_n)
            except AttributeError:
                pass

关于python - 通过重用代码和传递成员名称来运行测试来减少行数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20060105/

相关文章:

python - pyodbc导入错误: DLL load failed: The specified module could > not be found

java - 为什么我在 Hackerrank 上的这段代码中因超时而被终止?我的最后一次迭代没有发生?

php 列表到表中

c# - 比较字符串相似度

algorithm - 在 1-DOF 质量 Spring 系统中实现半隐式后向欧拉

python - tesseract 从表中读取值

Python 在 for 循环之外获取修改后的列表

python - 在 python pandas 中按组回归

python - 我的这部分代码(应该从其他 python 脚本中删除 Python 2 风格的注释)没有做任何事情。为什么?

java - 显示两个数组中不属于两个数组的元素