我正在尝试使用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
仅将对象与该特定名称解除绑定。如果对象是在其他地方引用的,在这种情况下是调用方中的army2
引用的,则该对象继续存在;否则,该对象将继续存在。 del
除了拒绝使用特定名称del
-ed的访问外,没有其他作用。
如果您必须具有这种行为,我建议两件事:
+
不会影响任何一个操作数,它应该产生一个带有两者之和/并置的全新对象。尽管+=
允许修改左手操作数,但不应修改右手操作数。重载运算符时,通常的经验法则是“Do n't”,后接“好,但前提是它遵守该运算符的预期语义”,并且这种情况肯定与+
或+=
的预期语义不匹配。 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
可能会违反您的班级的其他限制(因为可能期望班级的所有元素都具有composition
,包括'spear'
,'sword'
和'archer'
。如果这是一个问题,请不要对其进行clear
,只需将所有键重新分配给零,例如:
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
在返回'Response'(Python)中传递多个参数 - python我在Angular工作,正在使用Http请求和响应。是否可以在“响应”中发送多个参数。角度文件:this.http.get("api/agent/applicationaware").subscribe((data:any)... python文件:def get(request): ... return Response(seriali…
Python exchangelib在子文件夹中读取邮件 - python我想从Outlook邮箱的子文件夹中读取邮件。Inbox ├──myfolder 我可以使用account.inbox.all()阅读收件箱,但我想阅读myfolder中的邮件我尝试了此页面folder部分中的内容,但无法正确完成https://pypi.python.org/pypi/exchangelib/ 参考方案 您需要首先掌握Folder的myfo…
python JSON对象必须是str,bytes或bytearray,而不是'dict - python在Python 3中,要加载以前保存的json,如下所示:json.dumps(dictionary)输出是这样的{"('Hello',)": 6, "('Hi',)": 5}当我使用json.loads({"('Hello',)": 6,…
R'relaimpo'软件包的Python端口 - python我需要计算Lindeman-Merenda-Gold(LMG)分数,以进行回归分析。我发现R语言的relaimpo包下有该文件。不幸的是,我对R没有任何经验。我检查了互联网,但找不到。这个程序包有python端口吗?如果不存在,是否可以通过python使用该包? python参考方案 最近,我遇到了pingouin库。
Python ThreadPoolExecutor抑制异常 - pythonfrom concurrent.futures import ThreadPoolExecutor, wait, ALL_COMPLETED def div_zero(x): print('In div_zero') return x / 0 with ThreadPoolExecutor(max_workers=4) as execut…