Python 学习积累《二》 Python的内省机制

 Python的内省机制还是比较强大的。所谓内省,实际上主要是指在runtime获得一个对象的全部类型信息。这样可以提供更好的编程灵活性。
Java中的introspection是通过ReflectionAPI来做到的。Python中的内省主要是通过一下几个方法:

[1] type/str/dir
[2] getattr

我们先来看第一类方法:
在Python中,任何东西都是对象,看看下边这个例子:
type的作用是得到一个对象的类型。
str的作用类似于Java中的Object.toString()。把一个对象用一个字符串表示出来。
>>> import sys
>>> type(sys)
<type 'module'>
>>> str(sys)
"<module 'sys' (built-in)>"
>>>

第二类方法是得到对象的属性(成员变量和成员函数)的信息:
dir的作用是把一个对象的所有属性都列出来
getattr的作用是得到某一个特定的属性,返回值类似于C中的函数指针

>>> dir(sys)
['__displayhook__', '__doc__', '__excepthook__', '__name__', '__stderr__', '__stdin__', '__stdout__', '_getframe', 'api_version', 'argv', 'builtin_module_names', 'byteorder', 'call_tracing', 'callstats', 'copyright', 'displayhook', 'exc_clear', 'exc_info', 'exc_type', 'excepthook', 'exec_prefix', 'executable', 'exit', 'getcheckinterval', 'getdefaultencoding', 'getdlopenflags', 'getfilesystemencoding', 'getrecursionlimit', 'getrefcount', 'hexversion', 'last_traceback', 'last_type', 'last_value', 'maxint', 'maxunicode', 'meta_path', 'modules', 'path', 'path_hooks', 'path_importer_cache', 'platform', 'prefix', 'ps1', 'ps2', 'setcheckinterval', 'setdlopenflags', 'setprofile', 'setrecursionlimit', 'settrace', 'stderr', 'stdin', 'stdout', 'version', 'version_info', 'warnoptions']

>>> getattr(sys, 'setprofile')
<built-in function setprofile>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值