2016-03-04 196 views
1

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

default(int)0

default(decimal)0.0

default(MyCustomClassType)null

我希望这样的事情已经存在,因为我想从一个熊猫数据帧预处理值并用整数列中的0代替NaN,避免编写我自己的函数(包含每个可能类型的巨型开关,以模仿我前面例举的行为,从.NET开始)。

任何指针将不胜感激。谢谢。

+5

'INT()''返回由0'默认和'浮动()''返回由0.0'默认。这有帮助吗? – gtlambert

+0

@idjaw,并执行'x = something或int()'不满足相同的需求? – Chris

回答

2

正如在评论中指出,Python的类型,如intfloatstrlist等都是可赎回,即可以使用int()并获得0,或str()list(),并得到一个空字符串或列表。

>>> type(42)() 
0 

同样也适用于numpy类型。你可以使用dtype属性numpy的阵列的类型,然后用它来初始化“失踪”的价值观:

>>> 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在你的榜样的实例..

>>> class Foo(object): pass 
>>> type(Foo())() 
<__main__.Foo at 0x7f8b124c00d0> 
+0

这是非常好的,正是我所期待的,谢谢。 – user2916547