删除/添加对象到列表

时间:2019-03-30 07:12:39

标签: python

我的编码可以工作吗?该程序应在列表中搜索酒店,如果返回None,我可以在列表中添加新的酒店。

我特别需要str部分的帮助。

class Hotel:
    def __init__(self, name, address):
        self._name = name
        self._address = address

    @property
    def name(self):
        return self._name

    @property
    def address(self):
        return self._address

    def __str__(self):
        return "Hotel Name: {} Address: {}".format(self._name, self._address)

class TransportServices:
    def __init__(self):
        self._hotels    = [] 
        #self._bookings  = [] # as you can see i have two other list in this class
        #self._drivers   = []

    def searchHotel(self, name):
        for h in self._hotels:
            if h.name == name:
                return h
        return None


    def addHotel(self, hotel):
        h = self.searchHotel(hotel)
        if h is None:
            self._hotels.append(hotel)
            return True
        else:
            return False

    def __str__(self):
        hotels = [str(h) for h in self._hotels]
        return "Hotels\n{} ".format(self._hotels) # need help here

def main():

   hotel = TransportServices()
   hotel.addHotel(Hotel("123", "ABC"))
   hotel.addHotel(Hotel("234", "QWE"))


   print(hotel)

main()

3 个答案:

答案 0 :(得分:2)

问题出在您的

def searchHotel(self, name):
    for h in self._hotels:
        if h.name == name:
            return h
    return None

方法。您正在将h.namename进行比较,但是name不是字符串(例如h.name),而是一个Hotel对象。

尝试

def searchHotel(self, hotel):
    for h in self._hotels:
        if h.name == hotel.name:
            return h
    # return None is not necessary here, it's the default.

否则期望在此处传递一个字符串,然后在addHotel中执行:

h = self.searchHotel(hotel.name)

还请注意,如果两件事在逻辑上应该相同,则定义__eq__可能会很有用。如果任何两个酒店共用名称和地址,则它们应该是同一家酒店,因此您可以这样做

class Hotel:
    def __eq__(self, other: 'Hotel') -> bool:
        if not isinstance(other, self.__class__):
            return False
        return (self.name, self.address) == (other.name, other.address)

这样做的好处是可以简化searchHotel

def searchHotel(self, hotel):
    if hotel in self._hotels:
        return hotel

答案 1 :(得分:0)

它认为是因为您只是在打印TransportServices对象列表,所以请尝试使用searchHotel函数。

print(hotel.searchHotel("234"))

答案 2 :(得分:0)

问题出在您的return语句中。

更改

def __str__(self):
    hotels = [str(h) for h in self._hotels]
    return "Hotels\n{} ".format(self._hotels) # need help here

def __str__(self):
    hotels = [str(h) for h in self._hotels]
    return "Hotels\n{} ".format(hotels)