inspect使用(Python)

使用import inspect查看python 類的參數和模塊、函數代碼

 文件就是最小的模塊,文件夾是比較大的模塊。

文件裏面可以包含類,函數。

函數可以執行一個操作,多個函數組合在一起可以寫爲一個模塊,根據不同事物寫成一個類,這個類包含幾個行爲寫成幾個類內的函數,也可以將這些作爲一個文件。

主要步驟是將文件路徑設置到系統,再將文件作爲模塊引入,再開始查看文件裏面的內容。

 

首先,寫了一個函數

複製代碼
def h():
    print "hello"

def hm(m,k):
    print m, k


class w(object):
    def __init__(a, self):
        name =a
    def g(self):
        print name,"hello world!"
複製代碼

保存在路徑C:\下,起個名字叫hello.py

打開python shell 窗口,將這個路徑加入到系統路徑裏。命令如下

import sys

sys.path.append('C:/')

將文件當做一個模塊引入。

import hello

import inspect

 

查看整個模塊hello的源代碼: inspect.getsource(hello)  整個樣子不好看,需要print inspect.getsource(hello)

查看模塊hello裏面wo這個類的全部代碼  print inspect.getsource(hello.w)

查看模塊內某個函數的代碼: print inspect.getsource(hello.h)

查看模塊內某個類中函數的代碼 print inspect.getsource(hello.w.g)

 

查看模塊中某個函數的參數的代碼:inspect.getargspec(hello.hm)

查看模塊中類的參數代碼 inspect.getargspec(hello.w.__init__)   #這裏還是查看類的初始定義函數。

查看類中函數參數代碼 inspect.getargspec(hello.w.g)

查看模塊路徑 inspect.getabsfile(hello)  

查看文件夾模塊中某個類的路徑 inspect.getabsfile(。。。)#結果是顯示類的初始定義函數__init__.py的位置。

 

 

 >>> inspect.getabsfile(django.db)

'c:\\python27\\lib\\site-packages\\django-1.7.1-py2.7.egg\\django\\db\\__init__.py'

綜上,最重要的是要記住,

查看全部代碼 inspect.getsource(模塊.函數)或者(模塊.類.函數)

查看函數參數 inspect.getargspec(...)   查看類的參數,則括號裏爲(模塊.類.__init__)

查看函數的位置 inspect.getabsfile(...) 

 

這些應該夠學習用了。以後有什麼再補充。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章