hasattr函数

来源:互联网 发布:淘宝刷微淘粉丝 编辑:程序博客网 时间:2024/06/16 08:32

Python中可以判断一个对象有没有某个属性,可以使用hasattr()函数来进行。

例如,想要判断变量a是否具有"len"属性:

a=Noneif hasattr(a,'len'):    print aelse:    print "a doesn't have the attribute of 'len'."

运行结果:

a doesn't have the attribute of 'len'.

这对None值的判断比较有帮助,避免len等方法的失效。

0 0