获取对象信息
2015-10-09 19:47
260 查看
type()
判断函数类型
若一个变量指向函数或类,也可以用type()判断:
可以比较两个变量的type类型是否相同:
可通过导入types模块:
类型:
types.StringType
types.UnicodeType
types.ListType
types.TypeType
注:所有类型本身的类型都是TypeType
isinstance()
判断基本类型
判断基本类型(是否是某种类型中的一种)
判断继承关系
前提:继承关系如下:
object -> Animal -> Dog -> Husky
建立3种类型的对象:
判断如下:
dir()
获得一个对象的所有属性和方法,返回一个包含字符串的list
hasattr()、setattr()以及getattr()
测试该对象的属性:
判断函数类型
>>> type(123) <type 'int'>
若一个变量指向函数或类,也可以用type()判断:
>>> type(abs) <type 'builtin_function_or_method'> >>> type(a) <class '__main__.Animal'>
可以比较两个变量的type类型是否相同:
>>>type('world')==type(888) >>>False
可通过导入types模块:
>>> import types >>> type(u'abc')==types.UnicodeType >>>True
类型:
types.StringType
types.UnicodeType
types.ListType
types.TypeType
注:所有类型本身的类型都是TypeType
isinstance()
判断基本类型
>>> isinstance('abc', str) True
判断基本类型(是否是某种类型中的一种)
>>> isinstance('abc', (str, unicode)) True
判断继承关系
前提:继承关系如下:
object -> Animal -> Dog -> Husky
建立3种类型的对象:
>>> a = Animal() >>> d = Dog() >>> h = Husky()
判断如下:
>>> isinstance(h, Husky) True >>> isinstance(h, Dog) True >>> isinstance(h, Animal) True
dir()
获得一个对象的所有属性和方法,返回一个包含字符串的list
>>> dir('abc') ['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__getslice__', '__gt__', '__hash__', '__init__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '_formatter_field_name_split', '_formatter_parser', 'capitalize', 'center', 'count', 'decode', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'index', 'isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
hasattr()、setattr()以及getattr()
>>> class MyObject(object): ... def __init__(self): ... self.x = 9 ... def power(self): ... return self.x * self.x ... >>> obj = MyObject()
测试该对象的属性:
>>> hasattr(obj, 'x') # 有属性'x'吗? True >>> obj.x 9 >>> hasattr(obj, 'y') # 有属性'y'吗? False >>> setattr(obj, 'y', 19) # 设置一个属性'y' >>> hasattr(obj, 'y') # 有属性'y'吗? True >>> getattr(obj, 'y') # 获取属性'y' 19 >>> obj.y # 获取属性'y' 19
相关文章推荐
- 构造NFS
- web字体
- 6.5.2直接选择排序
- Flex工程部署到Tomcat的步骤
- 压力测试
- UESTC 84 Binary Operations(位运算+DP)
- HDU3068最长回文 Manacher算法
- servlet的上传文件
- 高精度运算之加减乘
- ffmpeg SDK开发手册
- Codeforces 8B
- POJ 1010 STAMPS(dfs)
- ActionBar之自定义分享
- 【work】判断ip地址是否合法
- 重启docker服务器后 遇到 'device or resource busy'错误
- 启动fiddler8888被占用
- [Leetcode]Sum Root to Leaf Numbers
- error LNK2019: 无法解析的外部符号
- 用python3写一个华工SCUT连接的脚本
- ios之viewWithTag