python中的自省

来源:互联网 发布:python ljust函数 编辑:程序博客网 时间:2024/04/30 22:15

python中的自省,介绍一下几个重要的函数:

 

dir 函数,传入的参数是对象,返回该对象的所有属性和函数列表:

>>> import string
>>> dir(string)
['Formatter', 'Template', '_TemplateMetaclass', '__builtins__', '__doc__', '__file__', '__name__', '__package__', '_float', '_idmap', '_idmapL', '_int', '_long', '_multimap', '_re', 'ascii_letters', 'ascii_lowercase', 'ascii_uppercase', 'atof', 'atof_error', 'atoi', 'atoi_error', 'atol', 'atol_error', 'capitalize', 'capwords', 'center', 'count', 'digits', 'expandtabs', 'find', 'hexdigits', 'index', 'index_error', 'join', 'joinfields', 'letters', 'ljust', 'lower', 'lowercase', 'lstrip', 'maketrans', 'octdigits', 'printable', 'punctuation', 'replace', 'rfind', 'rindex', 'rjust', 'rsplit', 'rstrip', 'split', 'splitfields', 'strip', 'swapcase', 'translate', 'upper', 'uppercase', 'whitespace', 'zfill']

可以看到, string 对象的所有函数,属性都列举出来了。

getattr 方法,传入参数是对象和该对象的函数或者属性的名字,返回对象的函数或者属性实例,如下:

>>> getattr(string,'__name__')
'string'


>>> getattr(string,'__doc__')
"A collection of string operations (most are no longer used).\n\nWarning: most of the code you see here isn't normally used nowadays.\nBeginning with Python 1.6, many of these functions are implemented as\nmethods on the standard string object. They used to be implemented by\na built-in module called strop, but strop is now obsolete itself.\n\nPublic module variables:\n\nwhitespace -- a string containing all characters considered whitespace\nlowercase -- a string containing all characters considered lowercase letters\nuppercase -- a string containing all characters considered uppercase letters\nletters -- a string containing all characters considered letters\ndigits -- a string containing all characters considered decimal digits\nhexdigits -- a string containing all characters considered hexadecimal digits\noctdigits -- a string containing all characters considered octal digits\npunctuation -- a string containing all characters considered punctuation\nprintable -- a string containing all characters considered printable\n\n"

>>> getattr(string,'split')   
<function split at 0x7ffd7fc60b18>

callable 方法,如果传入的参数是可以调用的函数,则返回 true ,否则返回 false 

>>> callable(getattr(string,'split'))
True
>>> callable(getattr(string,'__doc__'))
False

 

下面这段代码列出对象所有函数:

 

methodList = [method for method in dir(object) if callable(getattr(object,method))]

 

比如查看 string 的所有函数:

>>> methodlist= [method for method in dir(string) if callable(getattr(string,method))]
>>> methodlist
['Formatter', 'Template', '_TemplateMetaclass', '_float', '_int', '_long', '_multimap', 'atof', 'atof_error', 'atoi', 'atoi_error', 'atol', 'atol_error', 'capitalize', 'capwords', 'center', 'count', 'expandtabs', 'find', 'index', 'index_error', 'join', 'joinfields', 'ljust', 'lower', 'lstrip', 'maketrans', 'replace', 'rfind', 'rindex', 'rjust', 'rsplit', 'rstrip', 'split', 'splitfields', 'strip', 'swapcase', 'translate', 'upper', 'zfill']

0 0
原创粉丝点击