我有两个这样定义的类:
班级设施:
def __init__(self,name,openingCost):
self.name = name
self.openingCost = openingCost
self.connectionCosts = {}
def addConnection(self,cl,cost):
self.connectionCosts[cl] = cost
类客户端:
def __init__(self,name,demand):
self.name = name
self.demand = demand
self.connectionCosts = {}
def addConnection(self,fac,cost):
self.connectionCosts[fac] = cost
def isConnected(self,facName):
temp = Facility(facName,-1)
return temp in self.connectionCosts
isConnected方法用于检查名称为'facName'的设施是否在dict connectionCosts中
当我定义时: f1 =设施('ta',10), c1 =客户(“某些客户”,20), c1.addConnection(f1,3)
c1.addConnection返回False。我需要向Facility类添加哪些方法以确保其有效? (无法更改isConnected方法,很麻烦)
答案 0 :(得分:1)
您需要覆盖 eq 和 hash 方法来比较类对象 喜欢:
class Facility:
def __init__(self,name,openingCost):
self.name = name
self.openingCost = openingCost
self.connectionCosts = {}
def addConnection(self,cl,cost):
self.connectionCosts[cl] = cost
def __eq__(self, other):
return str(self.name) == str(other.name.name)
def __hash__(self):
return hash(self.name)