您的位置:首页 > 其它

获取对象信息

2015-10-09 19:47 260 查看
type()

判断函数类型

>>> 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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: