python识别图片数字traceract_如何将图形调用打印为树?
我可以比“吉咪”更好。下面是他的decorator的一個版本,它根據您在調用堆棧中的位置進行縮進和下移:import functools
# a factory for decorators
def create_tracer(tab_width):
indentation_level = 0
def decorator(f): # a decorator is a function which takes a function and returns a function
@functools.wraps(f)
def wrapper(*args): # we wish to extend the function that was passed to the decorator, so we define a wrapper function to return
nonlocal indentation_level # python 3 only, sorry
msg = " " * indentation_level + "{}({})".format(f.__name__, ", ".join([str(a) for a in args]))
print(msg)
indentation_level += tab_width # mutate the closure so the next function that is called gets a deeper indentation level
result = f(*args)
indentation_level -= tab_width
return result
return wrapper
return decorator
tracer = create_tracer(4) # create the decorator itself
@tracer
def f1():
x = f2(5)
return f3(x)
@tracer
def f2(x):
return f3(2)*x
@tracer
def f3(x):
return 4*x
f1()
輸出:
^{pr2}$
nonlocal語句允許我們在外部作用域中變異{}。在輸入函數時,我們增加縮進級別,以便下一個print得到進一步縮進。然后在退出時,我們再次減少它。在
這稱為decorator syntax。它純粹是“語法糖”;轉換成不帶@的等效代碼非常簡單。在@d
def f():
pass
與以下內容相同:def f():
pass
f = d(f)
如您所見,@只是以某種方式使用decorator來處理修飾函數,并用結果替換原來的函數,就像@jme的答案一樣。它類似于Invasion of the Body Snatchers;我們用看起來與f相似但行為不同的東西來代替{}。在
如果您停留在python2上,可以通過使用帶有實例變量的類來模擬nonlocal語句。如果您以前從未使用過裝飾器,這對您可能會更有意義。在# a class which acts like a decorator
class Tracer(object):
def __init__(self, tab_width):
self.tab_width = tab_width
self.indentation_level = 0
# make the class act like a function (which takes a function and returns a function)
def __call__(self, f):
@functools.wraps(f)
def wrapper(*args):
msg = " " * self.indentation_level + "{}({})".format(f.__name__, ", ".join([str(a) for a in args]))
print msg
self.indentation_level += self.tab_width
result = f(*args)
self.indentation_level -= self.tab_width
return result
return wrapper
tracer = Tracer(4)
@tracer
def f1():
# etc, as above
你提到你不能改變現有的功能。您可以通過使用globals()來復古裝修(盡管這通常不是一個好主意,除非您真的需要這樣做):for name, val in globals().items(): # use iteritems() in Python 2
if name.contains('f'): # look for the functions we wish to trace
wrapped_func = tracer(val)
globals()[name] = wrapped_func # overwrite the function with our wrapped version
如果您無法訪問相關模塊的源代碼,那么可以通過檢查導入的模塊并更改它導出的項來實現非常相似的功能。在
在這種情況下,天空就是極限。通過將調用存儲在某種圖形數據結構中,而不是簡單地縮進和打印,您可以將其構建到一個工業強度代碼分析工具中。然后,您可以查詢您的數據來回答諸如“本模塊中哪些函數被調用最多?”或者“哪個函數最慢?”。事實上,這對圖書館來說是個好主意。。。在
創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎總結
以上是生活随笔為你收集整理的python识别图片数字traceract_如何将图形调用打印为树?的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python短信接口_短信接口DEMO-
- 下一篇: python读取fiddler_pyth