我的python程序使用了dicts,并且有大量的"如果"仅用于检查检索值的类型的语句。
我想避免这种情况,而是采用更加编程的正确方式。
以下是一个例子:
(x:(Int, Int), y:String) => (x._1 + y.length, x._2 + 1),
(x:(Int, Int), y:(Int, Int)) => (x._1 + y._1, x._2 + y._2)
答案 0 :(得分:3)
要验证dict
的所有键/值是否属于特定类型,您可以使用all()
函数:
if all(isinstance(k, str) for k in playerdb):
print("all keys are strs")
要在存储值时强制执行类型,您可以使用自定义函数来调解对字典的访问,或者更好的是,子类dict
并覆盖__setitem__
方法,例如:
>>> class mydict(dict):
... def __setitem__(self, key, val):
... if not isinstance(key, str):
... raise ValueError("key must be a str")
... if not isinstance(val, int):
... raise ValueError("value must be an int")
dict.__setitem__(self, key, val)
...
>>> d = mydict()
>>> d["key"] = 1
>>> d["key"] = "value"
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 6, in __setitem__
ValueError: value must be an int
答案 1 :(得分:0)
Python不是类型安全的。因此,存储在字典中的值可以是任何类型。防止将其他类型的值添加到字典的一种方法是定义仅在类型匹配时添加数据的函数。然后只使用此函数附加到字典。
def gain_gold(playername, amount):
if isinstance(amount, int):
playerdb[playername] = amount
else:
raise Exception('invalid type')