Rya*_* WE -1 python dictionary types
我的Python程序使用字典,并且有大量的“if”语句只是为了检查检索到的值的类型。
我想避免这种情况,而是以更编程正确的方式进行。
这是一个例子:
# golddb should only contain str keys and int values
golddb = dict()
def gainGold(playername):
global golddb
golddb[playername] += 1 # error may happen if I try to += a non-int type
golddb[playername] = "hello" # I want python to give an error when I try to assign a str to be a value in the dict
Run Code Online (Sandbox Code Playgroud)
要验证 a 的所有键/值dict
是否属于特定类型,您可以使用以下all()
函数:
if all(isinstance(k, str) for k in playerdb):
print("all keys are strs")
Run Code Online (Sandbox Code Playgroud)
要在存储值时强制执行类型,您可以使用自定义函数来协调对字典的访问,或者更好的是,子类化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
Run Code Online (Sandbox Code Playgroud)