代码中经常会有变量是否为None的判断,有三种主要的写法:第一种是`if x is None`:第二种是 `if not x:`:第三种是`if not x is None`(这句这样理解更清晰`if not (x is None)`) .如果你觉得这样写没啥区别,那么你可就要小心了,这里面有一个坑.先来看一下代码: ? 1 2 3 4 5 6 7 8 9 10 11 12 >>> x = 1 >>> not x False >>> x = [1] &…
在实际写程序中,经常要对变量类型进行判断,除了用type(变量)这种方法外,还可以用isinstance方法判断: #!/usr/bin/env pythona = 1b = [1,2,3,4]c = (1,2,3,4)d = {‘a‘:1,‘b‘:2,‘c‘:3}e = "abc"if isinstance(a,int): print "a is int"else: print "a is not int"if isinstance…
这里有两种方法.type 和isinstance import types aaa = 0 print type(aaa) if type(aaa) is types.IntType: print "the type of aaa is int" if isinstance(aaa,int): print "the type of aaa is int" bbb = 'hello' print type(bbb) if type(bbb) is types.Stri…
http://www.cnblogs.com/starspace/archive/2008/12/03/1347007.html 第一种方法: 'var' in locals().keys() 第二种方法: try: print var except NameError: print 'var not defined' 第三种方法: 'var' in dir() 实际上写最好使用命名空间: 'varname' in locals().keys() 'varname' in dir() 或者 tr…
https://stackoverflow.com/questions/14808945/check-if-variable-is-dataframe Use the built-in isinstance() function. import pandas as pd def f(var): if isinstance(var, pd.DataFrame): print "do stuff" …