python函数代码_如何显示Python函数的代码?
這有點老套,但是如果這是您經常要做的事情,您可以使用readline模塊和函數修飾符。在class PrintableFunction(object):
"""A class that contains a function and its start and end points
in the readline history"""
def __init__(self, func, start, end):
self.start = start
self.end = end
self.func = func
def __call__(self, *args):
self.func(*args)
def __str__(self):
"""Just get all the readline history lines from start to end and
return them"""
lines = []
for i in range(self.start, self.end + 1):
lines.append(readline.get_history_item(i))
return "\n".join(lines)
class SavedFunction(object):
"""The actual function decorator. It takes one argument, the history
line that at which the function definition will begin."""
def __init__(self, start):
"""Take the starting line as an argument to the decorator. The end
line is grabbed from the current history after the function has
been entered"""
self.start = start
self.end = readline.get_current_history_length()
def __call__(self, func):
return PrintableFunction(func, self.start, self.end)
可以將這些類添加到PYTHONSTARTUP文件中,這樣每次加載解釋器時,都可以使用它們。在
^{pr2}$
我已經為自己創建了一個自定義的PS1(在PYTHONSTARTUP文件中),它顯示了當前的readline歷史編號,這意味著我可以快速地將其添加到@saved_function參數列表中,這比使用readline.get_current_history_length函數獲取它要容易得多:[508] @SavedFunction(509)
(509) def foo(bar):
(510) print(bar)
[511] print(foo)
def foo(bar):
print(bar)
總結
以上是生活随笔為你收集整理的python函数代码_如何显示Python函数的代码?的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: pytorch 对抗样本_《AI安全之对
- 下一篇: python变量声明语句_python