我有一個程序模擬王國和其他羣體(在我的代碼中稱爲「派系」)。我在這個程序中跟蹤派系聯盟的地方在哪裏?
class Faction:
def __init__(self, name, allies=[]):
self.name = name
self.allies = allies
def is_ally_of(self, other_faction):
if self in other_faction.allies:
return True
else:
return False
def become_ally(self, other_faction, both_ally=True):
""" If both_ally is false, this does *not* also
add self to other_faction's ally list """
if self.is_ally_of(other_faction):
print("They're already allies!")
else:
self.allies.append(other_faction)
if both_ally == True:
other_faction.become_ally(self, False)
RezlaGovt = Faction("Kingdom of Rezla")
AzosGovt = Faction("Azos Ascendancy")
我希望能夠become_ally()方法調用一個派別派別添加到盟友名單,像這樣:
RezlaGovt.become_ally(AzosGovt) # Now AzosGovt should be in RezlaGovt.allies,
# and RezlaGovt in AzosGovt.allies
什麼實際發生的是這樣的:
RezlaGovt.become_ally(AzosGovt)
# prints "They're already allies!"
# now AzosGovt is in the allies list of both AzosGovt and RezlaGovt,
# but RezlaGovt isn't in any allies list at all.
每當我嘗試調用become_ally()時,代碼應該檢查以確保它們不是盟友。這是不工作的部分。每次我打電話給become_ally()時,它會打印出「他們已經是盟友!」,無論他們是否真的是。
我也試過使用if self in other_faction.allies:
,但是那個問題相同。
我強烈懷疑問題在於我使用了self
,但我不知道Google會向Google瞭解哪些條款以獲取更多信息。
作爲一個側面說明'如果x在Y:返回否則真:返回FALSE'可以簡化爲'返回X在y' – Neitsa
和'如果x ==真:'是_usually_最好表示爲'如果x:'(它接受任何真實的東西,但Pythonic代碼通常不會在使用'bool'時特別掛斷。 – ShadowRanger