我的python程序使用dicts,有大量的“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
要验证} 函数:
dict
的所有键/值是否属于特定类型,可以使用^{为了在存储值时强制使用类型,可以使用自定义函数来调解对字典的访问,或者更好地,使用子类}方法,例如:
^{pr2}$dict
并重写{Python不是类型安全的。因此,存储在字典中的值可以是任何类型的。防止将其他类型的值添加到字典中的一种方法是定义一个函数,该函数只在类型匹配时添加数据。然后只使用此函数附加到字典中。在
相关问题 更多 >
编程相关推荐