假设我想在 python 中创建一个函数,只返回给定类型的默认值作为参数:
def PrintDefaultValue(valueType: type):
print(default(type)) // ?? # <-- how I get that with a type instance
例如,如果我得到列表类型,它应该返回一个空列表。 如果我得到一个字符串作为类型,它应该返回“”。 如果我得到一个整数作为类型,它应该返回 0。
from collections import defaultdict
def PrintDefaultValue(valueType: type):
default_values = defaultdict(
lambda: None, # Default factory for unknown types
{int: 0, float: 0.0, str: "", list: [], dict: {}, bool: False}
)
default_value = default_values[valueType]
print(default_value)