38. 什么是Python自省 ------------------------- python自省可以理解python中对变量或对象自身的解释,因为python的变量类型并不是非常清晰 的,需要通过一些内建的函数来找出其变量类型及其成员函数等。 另外在运行时,变量经过多次传递和赋值也需要通过函数找出其类型及其类型信息。 一句话总结就是,自省关心的是找出对象的内在特征,例如属性等。 自省API包含以下两个: * type(x) 返回变量x的类型, 即x.__class__ 。 * dir(T) 对于模块对象,返回模块的属性,对于类对象,返回他的属性和基类属性。 以下两个也可以认为是自省函数。 * getattr(),从对象中获取其属性。 * isinstance(), 判断对象是否是某个类的对象。 例如以下为type()函数的使用,输出变量a的类型 :: >>> a = 10 >>> type(a) >>> a = 'a' >>> type(a) 以下为对dir()函数的使用,输出变量a和i的属性和函数 :: >>> a = 'a' >>> dir(a) ['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__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'] >>> i = 10 >>> dir(i) ['__abs__', '__add__', '__and__', '__bool__', '__ceil__', '__class__', '__delattr__', '__dir__', '__divmod__', '__doc__', '__eq__', '__float__', '__floor__', '__floordiv__', '__format__', '__ge__', '__getattribute__', '__getnewargs__', '__gt__', '__hash__', '__index__', '__init__', '__init_subclass__', '__int__', '__invert__', '__le__', '__lshift__', '__lt__', '__mod__', '__mul__', '__ne__', '__neg__', '__new__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__', '__ror__', '__round__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruediv__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truediv__', '__trunc__', '__xor__', 'bit_length', 'conjugate', 'denominator', 'from_bytes', 'imag', 'numerator', 'real', 'to_bytes'] 变量i和a分别为整型变量和字符串,dir将输出其成员变量和成员方法列表。 可以从PEP 252得到更多的信息。