Quantcast
Channel: GameDev.net
Viewing all articles
Browse latest Browse all 17825

Which approach would be best for checking if an inventory is full in Python?

$
0
0
Here are 3 versions of a method from my inventory class that adds an item to the given inventory (or increases the items quantity). From a Python perspective, which approach would be best? Each method is followed by a sample of how I would use it in practice. I've been pretty interested in code design/architecture lately and I've been trying to get better at Python, so it may seem like a silly question but I'm just curious what you people think. Currently, I'm using approach #1, but I find it misleading that you could add an item and not actually have an item added. And if there's another approach not listed here that would be good please let me know. #1 prevent adding item if is_full(): def add_item(self, item): i = next((i for i in self.items if i.tag == item.tag), None) #Duplicate item... if i is not None: i.quantity += item.quantity elif not self.is_full(): self.items.append(item) player_inventory.add_item(item) #2 throw exception if is_full() and handle outside method: def add_item(self, item): i = next((i for i in self.items if i.tag == item.tag), None) if i is not None: i.quantity += item.quantity elif not self.is_full(): self.items.append(item) else: raise InvetoryFullException("Inventory can only hold 8 items.") try: player_inventory.add_item(item) except InvetoryFullException: pass #3 check if inventory is_full() outside of method: def add_item(self, item): i = next((i for i in self.items if i.tag == item.tag), None) if i is not None: i.quantity += item.quantity else: self.items.append(item) if not player_inventory.is_full(): player_inventory.items.append(item)

Viewing all articles
Browse latest Browse all 17825

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>