一些提示:
- PEP8 建议函数使用 underescored_names(而不是 camelCaseNames)
- 不要使用类型,如果你必须检查类型使用
isinstance
函数
- 检查类型通常是 Python 中的代码异味 - 使用鸭子类型或更改算法
这对我有用:
>>> def reset_inv(inventory):
if isinstance(inventory, list):
return []
elif isinstance(inventory, dict):
return {}
elif isinstance(inventory, str):
return 'nothing in inventory'
elif isinstance(inventory, bool):
return False
else:
return 'not inventory type'
>>> reset_inv([1, 2, 3])
[]
>>> reset_inv({"a": 1})
{}
>>> reset_inv("foo")
'nothing in inventory'
>>> reset_inv(True)
False
>>> reset_inv(0.1)
'not inventory type'
编写库存系统的惯用方式可能会使用普通列表或字典作为对象的容器。下面我使用字符串,但您可能应该为具有价值、重量等属性的库存项目编写一个类。
>>> from collections import Counter
>>> class Inventory(object):
def __init__(self, items = None):
if items is None:
self.reset()
else:
self.items = items
def reset(self):
self.items = []
def report(self):
if not self.items:
print("Your sac is empty.")
return
print("You have {} items in your sac.".format(len(self.items)))
counter = Counter(self.items).items()
for count, item in counter:
print("{: >3} {}".format(item, count))
>>> inv = Inventory(['knife', 'rock', 'rock', 'cloth'])
>>> inv.report()
You have 4 items in your sac.
1 cloth
1 knife
2 rock
>>> inv.items.append('coin')
>>> inv.report()
You have 5 items in your sac.
1 cloth
1 coin
1 knife
2 rock
>>> inv.items.remove('rock')
>>> inv.report()
You have 4 items in your sac.
1 cloth
1 coin
1 knife
1 rock
>>> inv.reset()
>>> inv.report()
Your sac is empty.