[py]python自省工具

Python 自省指南

在日常生活中,自省(introspection)是一种自我检查行为。自省是指对某人自身思想、情绪、动机和行为的检查。伟大的哲学家苏格拉底将生命中的大部分时间用于自我检查,并鼓励他的雅典朋友们也这样做。他甚至对自己作出了这样的要求:“未经自省的生命不值得存在。”

自省,自己能做什么? 写上自己的功能,以便于展示.

  • 对象属于那个类(获取类名)
  • 对象的内存id是多少
  • 对象的类型
  • 对象的值
  • 对象是否可调用
  • 对象如有__doc__属性,输出doc
  • 对象是否有这个属性
  • 是否是别类的子类

python自省工具

def interrogate(item):
    """Print useful information about item."""
    if hasattr(item, '__name__'):
        print "NAME:    ", item.__name__
    if hasattr(item, '__class__'):
        print "CLASS:   ", item.__class__.__name__
    print "ID:      ", id(item)
    print "TYPE:    ", type(item)
    print "VALUE:   ", repr(item)
    print "CALLABLE:",
    if callable(item):
        print "Yes"
    else:
        print "No"
    if hasattr(item, '__doc__'):
        doc = getattr(item, '__doc__')
    doc = doc.strip()   # Remove leading/trailing whitespace.
    firstline = doc.split('
')[0]
    print "DOC:     ", firstline

>>> interrogate('a string')     # String object
CLASS:    str
ID:       141462040
TYPE:     <type 'str'>
VALUE:    'a string'
CALLABLE: No
DOC:      str(object) -> string


>>> interrogate(42)             # Integer object
CLASS:    int
ID:       135447416
TYPE:     <type 'int'>
VALUE:    42
CALLABLE: No
DOC:      int(x[, base]) -> integer


>>> interrogate(interrogate)    # User-defined function object
NAME:     interrogate
CLASS:    function
ID:       141444892
TYPE:     <type 'function'>
VALUE:    <function interrogate at 0x86e471c>
CALLABLE: Yes
DOC:      Print useful information about item.
- 告知python版本等
>>> python

- 获取keywords
>>> help()
help> keywords

- 获取modules
>>> help('modules')

- 获取python可执行路径
>>> import sys
>>> sys.executable
'/usr/local/bin/python'

- 获取系统平台
>>> sys.platform
'linux2'

- 获取系统版本
>>> sys.version
'2.2.2 (#1, Oct 28 2002, 17:22:19) 
[GCC 3.2 (Mandrake Linux 9.0 3.2-1mdk)]'
>>> sys.version_info
(2, 2, 2, 'final', 0)

- 获取系统支持最大的整数
>>> sys.maxint
2147483647

- 获取参数
>>> sys.argv
['']

- 获取模块搜索路径
>>> sys.path

- 获取当前装入的模块
>>> sys.modules

>>> help('modules keywords')

- 获取模块的属性和方法
>>> dir(keyword)

- 文档字符串
>>> Person.__doc__

- 对象的名称是什么?
- 这是哪种类型的对象?
- 对象知道些什么?
- 对象能做些什么?
- 对象的父对象是谁?
原文地址:https://www.cnblogs.com/iiiiiher/p/8295275.html