设为首页 加入收藏

TOP

python 面向对象五 获取对象信息 type isinstance getattr setattr hasattr(一)
2017-12-18 12:36:52 】 浏览:143
Tags:python 面向 对象 获取 信息 type isinstance getattr setattr hasattr

一、type()函数

判断基本数据类型可以直接写intstr等:

 1 >>> class Animal(object):
 2 ...     pass
 3 ... 
 4 >>> type(123)
 5 <class 'int'>
 6 >>> type('123')
 7 <class 'str'>
 8 >>> type(None)
 9 <class 'NoneType'>
10 >>> type(abs)
11 <class 'builtin_function_or_method'>
12 >>> type(Animal())
13 <class '__main__.Animal'>
1 >>> type(123) == type(456)
2 True
3 >>> type(123) == int
4 True

判断一个对象是否是函数:

 1 >>> import types
 2 >>> def fn():
 3 ...     pass
 4 ...
 5 >>> type(fn)==types.FunctionType
 6 True
 7 >>> type(abs)==types.BuiltinFunctionType
 8 True
 9 >>> type(lambda x: x)==types.LambdaType
10 True
11 >>> type((x for x in range(10)))==types.GeneratorType
12 True

二、isinstance()函数

对于class的继承关系来说,使用type()就很不方便。如果要判断class的类型,可以使用isinstance()函数。

 1 >>> class Animal(object):
 2 ...     pass
 3 ... 
 4 >>> class Dog(Animal):
 5 ...     pass
 6 ... 
 7 >>> d = Dog()
 8 >>> isinstance(d, Dog)
 9 True
10 >>> isinstance(d, Animal)
11 True

用isinstance()判断基本类型:

1 >>> isinstance('a', str)
2 True
3 >>> isinstance(123, int)
4 True
5 >>> isinstance(b'a', bytes)
6 True

并且还可以判断一个变量是否是某些类型中的一种,比如下面的代码就可以判断是否是list或者tuple:

1 >>> isinstance([1, 2, 3], (list, tuple))
2 True
3 >>> isinstance((1, 2, 3), (list, tuple))
4 True

优先使用isinstance()判断类型,可以将指定类型及其子类“一网打尽”。

三、dir()函数

如果要获得一个对象的所有属性和方法,可以使用dir()函数,它返回一个包含字符串的list,比如,获得一个str对象的所有属性和方法:

>>> dir('abc')
['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']

列表中类似__xxx__的属性和方法在Python中都是有特殊用途的,比如__len__方法返回长度。在Python中,如果你调用len()函数试图获取一个对象的长度,实际上,在len()函数内部,它自动去调用该对象的__len__()方法,所以,下面的代码是等价的:

1 >>> len('abc')
2 3
3 >>> 'abc'.__len__()
4 3

自己写的类,如果也想用len(myObj)的话,就自己写一个__len__()方法:

1 >>> class MyDog(object):
2 ...     def __len__(self):
3 ...         return 100
4 ... 
5 >>> dog = MyDog()
6 >>> len(dog)
7 100

列表中剩下的都是普通属性或方法,比如lower()返回小写的字符串:

1 >>> 'abc'.upper()
2 'ABC'

四、getattr()setattr()以及hasattr()

测试该对象的属性:

 1 >>> class MyObject(object):
 2 ...     def __init__(self):
 3 ...         self.x = 9
 4 ...     def power(self):
 5 ...         return self.x * self.x
 6 ... 
 7 >>> obj = MyObject()
 8 >>> hasattr(obj, 'x')
 9 True
10 >>> hasattr(obj, 'y')
11 False
12 >>> 
13 >
首页 上一页 1 2 下一页 尾页 1/2/2
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇python 面向对象四 继承和多态 下一篇Python自动化--语言基础3--字典、..

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目