python - 添加后删除实例

标签 python oop

我正在尝试使用 Python 学习 OOP。我想知道如何创建军队,当我合并它们时,删除与指定军队合并的军队。

class Army:
    def __init__(self, spear, sword, archer):
        self.composition = {'spear': spear, 'sword': sword, 'archer': archer}

    def __add__(self, other):
        for item in other.composition:
            self.composition[item] += other.composition[item]
        del other

然后在控制台输入:

army1 = Army(10, 20, 30)
army2 = Army(30, 5, 0)
army1+army2

不会删除 army2。但是,如果我键入 del army2,它会删除实例...

最佳答案

这不起作用的原因是原始名称上的 del 只会解除对象与该特定名称的绑定(bind)。如果该对象在别处被引用,在本例中为调用者中的 army2,则该对象继续存在; del 除了拒绝以特定名称 del-ed 进行访问外没有其他效果。

如果你必须有这种行为,我推荐两件事:

  1. 不要为此行为重载运算符; + 预计不会影响任何一个操作数,它应该产生一个全新的对象,其中包含两者的总和/连接。虽然允许 += 修改左手操作数,但它不应该修改右手操作数。重载运算符时,通常的经验法则是“不要”,然后是“可以,但前提是它遵守该运算符的预期语义”,这种情况肯定不符合任何 的预期语义++=
  2. 现在我们已经决定使用一种方法,您可以通过移除另一支军队的内容来从另一支军队中移除部队。例如:

    class Army:
        def __init__(self, spear, sword, archer):
            self.composition = {'spear': spear, 'sword': sword, 'archer': archer}
    
        def absorb_army(self, other):  # or transfer_troops or whatever
            '''Removes all the troops from other, combining them with the troops of self'''
            for item in other.composition:
                self.composition[item] += other.composition[item]
            other.composition.clear()  # Leaves other.composition empty
    
    army1 = Army(10, 20, 30)
    army2 = Army(30, 5, 0)
    army1.absorb_army(army2)
    # army2 still exists, but all the troops in it are gone, moved to army1
    

请注意,我编写的 absorb_army 可能会违反您类(class)的其他约束(因为您类(class)的所有元素可能都应该具有 composition include 'spear' 'sword''archer'。如果这是一个问题,请不要清除,只需重新分配所有键为零,例如:

        def absorb_army(self, other):
            for item in other.composition:
                self.composition[item] += other.composition[item]
                other.composition[item] = 0  # Zero after adding to self

关于python - 添加后删除实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59252433/

相关文章:

java - 使用域对象作为键是一种好习惯吗?

c# - 如何组织相互继承但又具有相互继承的属性的 C# 类?

python - Jinja 使用 for 列出嵌套 JSON

python - 基于 Python 列表从 yaml 文件中检索数据

java - 如果提供了字段名称,如何一般填充对象?

excel - 列出 VBA 2003 中类的属性

java - 如何以OO方式修改返回值设计?

python - 我可以一次设置所有加载模块的日志记录级别吗?

python - matplotlib 中的多行 x 刻度标签

python - 虽然真正的循环在 python 中的另一个内部不起作用