Python酒店管理代码功能验证及__str__方法优化求助
Fixing Your Hotel Search & Add Code
Hey there! Let's walk through fixing the issues in your code, especially the __str__ method and a key bug in the add logic.
Key Issues Identified
- Wrong argument in
addHotel: You're passing a fullHotelobject tosearchHotel, but that method expects a hotel name string. This means your code will never detect duplicate hotels and will keep adding duplicates. - Broken
__str__forTransportServices: You created a list of human-readable hotel strings, but then printed the raw list ofHotelobjects (which shows memory addresses instead of useful info).
Corrected Full Code
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 = [] # self._drivers = [] def searchHotel(self, name): for h in self._hotels: if h.name == name: return h return None def addHotel(self, hotel): # Fix: Pass the hotel's name to searchHotel, not the whole object h = self.searchHotel(hotel.name) if h is None: self._hotels.append(hotel) return True else: return False def __str__(self): hotels = [str(h) for h in self._hotels] # Fix: Join the hotel strings with newlines for clean output return "Registered Hotels:\n{}".format("\n".join(hotels)) def main(): hotel_service = TransportServices() # Add first hotel (will succeed) print(hotel_service.addHotel(Hotel("123", "ABC"))) # Output: True # Try adding duplicate (will fail) print(hotel_service.addHotel(Hotel("123", "XYZ"))) # Output: False # Add a new unique hotel hotel_service.addHotel(Hotel("234", "QWE")) # Print the full list of hotels print(hotel_service) main()
What Changed & Why
Fixed
addHotellogic:- Changed
searchHotel(hotel)tosearchHotel(hotel.name)so we're actually searching by the hotel's name (matching whatsearchHotelexpects). Now duplicate hotels with the same name will be rejected.
- Changed
Improved
__str__methods:- Tweaked
Hotel.__str__to add a|for better readability (optional, but makes output cleaner). - Updated
TransportServices.__str__to use"\n".join(hotels)instead of printingself._hotels. This converts eachHotelobject to its human-readable string form and displays them one per line.
- Tweaked
Added test for duplicates:
- In
main(), I added a test to try adding a duplicate hotel, so you can see theaddHotelmethod correctly returnsFalsefor duplicates.
- In
Sample Output
When you run the corrected code, you'll get:
True False Registered Hotels: Hotel Name: 123 | Address: ABC Hotel Name: 234 | Address: QWE
内容的提问来源于stack exchange,提问作者user11099823
相关产品推荐
相关产品推荐

