代码之家  ›  专栏  ›  技术社区  ›  Ahmed Younes

类变量在for循环中保持为空

  •  0
  • Ahmed Younes  · 技术社区  · 6 年前

    我想确认一下 hotel_name 不存在于 Hotel.hotels 列表 看来,每当我开始进食循环查看空列表。

    注意如果我没有使用for循环并且只使用

    Hotel.hotels.append([number,hotel_name,city,total_number,empty_rooms])
    

    打印酒店名单

    [[1, 'Crown Plaza', 'alex', 20, 2], [1, 'Crown Plaza', 'alex', 20, 2], [2, 'Radisson Blu', 'cairo', 24, 22], [3, 'Paradise Inn', 'dubai', 390, 200], [4, 'Four Seasons', 'alex', 1000, 400], [5, 'Address', 'dubai', 500, 200], [6, 'Fairmont', 'dubai', 1000, 100], [7, 'Rotana', 'dubai', 5000, 300]]
    [Finished in 0.1s]
    

    这是文件

    class Hotel():
        """""""""
        this is hotel class file
        """
        hotels = []
    
        def __init__(self,number,hotel_name,city,total_number,empty_rooms):
            self.number = number
            self.hotel_name = hotel_name
            self.city = city
            self.total_number = total_number
            self.empty_rooms = empty_rooms
            for i in Hotel.hotels:
                if self.hotel_name not in i:
                    Hotel.hotels.append([number,hotel_name,city,total_number,empty_rooms])
                # else:
                #     print "Hotel already exists!"
    
    feed_dataBase_with_hotel = Hotel(1,"Crown Plaza","alex",20,2)
    feed_dataBase_with_hotel = Hotel(1,"Crown Plaza","alex",20,2)# cull repeated
    feed_dataBase_with_hotel = Hotel(2,"Radisson Blu","cairo",24,22)
    feed_dataBase_with_hotel = Hotel(3,"Paradise Inn","dubai",390,200)
    feed_dataBase_with_hotel = Hotel(4,"Four Seasons","alex",1000,400)
    feed_dataBase_with_hotel = Hotel(5,"Address","dubai",500,200)
    feed_dataBase_with_hotel = Hotel(6,"Fairmont","dubai",1000,100)
    feed_dataBase_with_hotel = Hotel(7,"Rotana","dubai",5000,300)
    
    print Hotel.hotels
    

    非常感谢帕特里克的回答 更新 如果我想从dict构建一个列表,因为我想访问空房间并用另一个类更改它的值

    class Hotel():
        """
        this is hotel class file
        """
        hotels = {}
        hotelList = []
    
        def __init__(self,number,hotel_name,city,total_number,empty_rooms):
            self.number = number
            self.hotel_name = hotel_name
            self.city = city
            self.total_number = total_number
            self.empty_rooms = empty_rooms
    
            # edited: no for needed
            if self.hotel_name in Hotel.hotels:
                print('Hotel {} Already exists!'.format(self.hotel_name))
                return # or raise ValueError & handle it
    
            Hotel.hotels[self.hotel_name] = self
    
            tempList = Hotel.hotels.items()
            for i in tempList:
                x = Hotel.hotels.items()[i][1]
                Hotel.hotelList.append(x)
    

    更新

    预订的另一个类将使用我们在品位酒店使用的实例变量HoTeleNoDe。

    from hotel import Hotel
    from customer import Customer
    from notification import Notification
    
    class Reservation():
        reservations =[]
        def reserve_room(self,hotel_name, customer_name):
            x = Hotel.hotels.values()
            for i in x:
                if Hotel.hotel_name in i:
                    Reservation.reservations.append([hotel_name,customer_name])
                    i[4] -=1
    

    属性错误:类酒店没有属性“hotel\u name”

    更新 Understanding getitem method 使用

    def __getitem__(self, hotel_name):
              return self.hotel_name
    

    问题解决了!

    特别感谢 Patrick

    3 回复  |  直到 6 年前
        1
  •  1
  •   Patrick Artner    6 年前

    我建议换些东西来修:

    • 您正在迭代一个可能有1000个 Hotel 如果你有一个相同的名字,如果你用A做的话会更好。 set dict 就像在那些 O(1) . List S有 O(n) 查找最坏情况时间,意义 set/dict 时间是恒定的,不管有多少 酒店 你有。名单越来越慢,越多 酒店 你需要搜索。

    • 你用新的酒店实例覆盖了相同的变量,它们自己被创建和遗忘——你只把你的愤怒值储存在你的内部。 Hotel.hotels 列表而不是存储构造的 酒店 本身。整个建筑 酒店 实例是没有意义的。

    拟议变更:

    • 让静态存储一个字典,让你有快速查找的好处。
    • 储存你的 酒店 -实例而不是您创建的值 酒店 带着
    • 不打印 Hotel.hotelDict 直接-我引入了一个方法,它只接受dict的值并按顺序打印它们-作为默认值,我按 Hotel.number

    class Hotel():
        """""""""
        this is hotel class file
        """   
        hotelDict = {} # checking "in" for sets is much faster then list - a dict is similar
                       # fast in checking and can hold values - serves double duty here
        # sorted hotels by value, sorted by key
    
        @classmethod
        def getSortedHotels(cls, sortKey = lambda x:x.number):
            """Takes all values (Hotel's) from Hotel.hotelDict
            and prints them after sorting. Default sort key is Hotel.number"""
            return sorted(cls.hotelDict.values(), key=sortKey) 
    
        def __init__(self,number,hotel_name,city,total_number,empty_rooms):
            if hotel_name in Hotel.hotelDict:
                print("Hotel already exists: {}".format(hotel_name))
                return # or raise ValueError("Hotel already exists") and handle the error
    # see https://stackoverflow.com/questions/3209233/how-to-replace-an-instance-in-init
    # if you want to try to replace it using __new__() but not sure if its possible
    
            self.number = number
            self.hotel_name = hotel_name
            self.city = city
            self.total_number = total_number
            self.empty_rooms = empty_rooms
            Hotel.hotelDict[self.hotel_name] = self
    
        def __repr__(self):
            """Neater print output when printing them inside a list"""
            return "{:>3}) {} in {} has {} of wich {} are empty.".format(
            self.number,self.hotel_name,self.city,self.total_number,self.empty_rooms)
            # if you want a "simple" list-like output of your attributes:
            # comment the return above and uncomment:
            # return repr([self.number,self.hotel_name,self.city,
            #              self.total_number,self.empty_rooms])
    
        def __str__(self):
            """Neater print output when printing Hotel instances"""
            return self.__repr__()
    

    测试:

    feed_dataBase_with_hotel = Hotel(1,"Crown Plaza","alex",20,2)
    feed_dataBase_with_hotel = Hotel(1,"Crown Plaza","alex",20,2) # cull repeated
    feed_dataBase_with_hotel = Hotel(2,"Radisson Blu","cairo",24,22)
    feed_dataBase_with_hotel = Hotel(3,"Paradise Inn","dubai",390,200)
    feed_dataBase_with_hotel = Hotel(4,"Four Seasons","alex",1000,400)
    feed_dataBase_with_hotel = Hotel(5,"Address","dubai",500,200)
    feed_dataBase_with_hotel = Hotel(6,"Fairmont","dubai",1000,100)
    feed_dataBase_with_hotel = Hotel(7,"Rotana","dubai",5000,300)
    
    print Hotel.getSortedHotels() 
    
    print Hotel(99,"NoWayInn","NoWhere",1,200)
    

    输出:

    Hotel already exists: Crown Plaza
    [  1) Crown Plaza in alex has 20 of wich 2 are empty.,   
       2) Radisson Blu in cairo has 24 of wich 22 are empty.,   
       3) Paradise Inn in dubai has 390 of wich 200 are empty.,   
       4) Four Seasons in alex has 1000 of wich 400 are empty.,   
       5) Address in dubai has 500 of wich 200 are empty.,   
       6) Fairmont in dubai has 1000 of wich 100 are empty.,   
       7) Rotana in dubai has 5000 of wich 300 are empty.]
    
     99) NoWayInn in NoWhere has 1 of wich 200 are empty.
    

    如果您希望按名称对酒店进行排序,请执行以下操作:

    print Hotel.getSortedHotels(sortKey=lambda x:x.hotel_name)
    
        2
  •  0
  •   Innuendo    6 年前

    看看这条线 对于我在Hotel.Hotels: 在这里

    for i in Hotel.hotels:
        if self.hotel_name not in i:
              Hotel.hotels.append([number,hotel_name,city,total_number,empty_rooms])
    

    试着让它填满你的数组

        3
  •  0
  •   hoploop    6 年前

    问题是在遍历空的“hotels”列表时添加。 首先检查for循环中现有的HORTLE名称,然后追加。

    for hotel in self.hotels:
        if self.hotel_name == hotel[1]:  # hotel_name is at index 1
            print('Already exists!')
            return  # return before appending
    #now append
    self.hotels.append([number,hotel_name,city,total_number,empty_rooms])
    

    如果你不想回来,试试这个

    for hotel in self.hotels:
        if self.hotel_name == hotel[1]:  # hotel_name is at index 1
            print('Already exists!')
            break
    else:  # break did not happen
        self.hotels.append([number,hotel_name,city,total_number,empty_rooms])