Python3 - 类型默认值的默认关键字?

时间:2016-03-04 14:50:26

标签: python python-3.x

Python3是否有类似.NET的default keyword?也就是说,给定一个类型,它会产生该类型的值,通常称为该值的默认值。例如:

default(int)0

default(decimal)0.0

default(MyCustomClassType)null

我希望这样的事情已经存在,因为我想从pandas数据帧中预处理值并用0替换整数列等NaNs,并避免编写我自己的函数(每个函数包含一个巨大的开关)可能的类型,模仿我之前举例说明的行为,来自.NET)。

任何指针都将非常感激。谢谢。

1 个答案:

答案 0 :(得分:2)

正如评论中所述,intfloatstrlist等Python类型都是可调用的,即您可以使用{{1} }并获取int(),或0str()并获取一个空字符串或列表。

list()

同样适用于>>> type(42)() 0 类型。您可以使用numpy属性获取numpy数组的类型,然后使用它来初始化" missing"值:

dtype

这也适用于提供no-args构造函数的其他类,但是,结果将是该类的实例,而不是像示例中的>>> A = np.array([1, 2, 3, 4, float("nan")]) # common type is float64 >>> A array([ 1., 2., 3., 4., nan]) >>> A[np.isnan(A)] = A.dtype.type() # nan is replaced with 0.0 >>> A array([ 1., 2., 3., 4., 0.]) >>> B = np.array([1, 2, 3, -1, 5]) # common type is int64 >>> B array([ 1, 2, 3, -1, 5]) >>> B[B == -1] = B.dtype.type() # -1 is replaced with >>> B array([1, 2, 3, 0, 5]) ..

null