1、获取对象类型,基本类型可以用type()来判断。
>>> type(123) <class \'int\'> >>> type(\'str\') <class \'str\'> >>> type(None) <type(None) \'NoneType\'>
2、如果想获得一个对象的所有属性和方法,可以使用dir()函数返回包含字符串的list。
>>> dir(\'ABC\') [\'__add__\', \'__class__\',..., \'__subclasshook__\', \'capitalize\', \'casefold\',..., \'zfill\']
知识点扩展:
使用type()
首先,我们来判断对象类型,使用type()函数:
基本类型都可以用type()判断:
>>> type(123) <type \'int\'> >>> type(\'str\') <type \'str\'> >>> type(None) <type \'NoneType\'>
如果一个变量指向函数或者类,也可以用type()判断:
>>> type(abs) <type \'builtin_function_or_method\'> >>> type(a) <class \'__main__.Animal\'>
但是type()函数返回的是什么类型呢?它返回type类型。如果我们要在if语句中判断,就需要比较两个变量的type类型是否相同:
>>> type(123)==type(456) True >>> type(\'abc\')==type(\'123\') True >>> type(\'abc\')==type(123) False
但是这种写法太麻烦,Python把每种type类型都定义好了常量,放在types模块里,使用之前,需要先导入:
>>> import types >>> type(\'abc\')==types.StringType True >>> type(u\'abc\')==types.UnicodeType True >>> type([])==types.ListType True >>> type(str)==types.TypeType True
© 版权声明
THE END
暂无评论内容