2012-03-27 63 views
11

我編程在Python,和我想知道如果我可以測試是否一個函數被調用我的代碼找出一個函數被調用

def example(): 
    pass 
example() 
#Pseudocode: 
if example.has_been_called: 
    print("foo bar") 

我將如何做到這一點?

+0

我寫了一個[計數裝飾](HTTP: //code.activestate.com/recipes/577534-counting-decorator/?in=user-4173873)在應用時會告訴你函數被調用了多少次。如果你願意,你可以根據自己的需要進行調整。 – 2012-03-27 02:20:54

+0

你希望如何處理這些信息? – 2012-03-27 02:36:03

回答

20

如果是OK的功能,要知道自己的名字,你可以使用一個功能屬性:

def example(): 
    example.has_been_called = True 
    pass 
example.has_been_called = False 


example() 

#Actual Code!: 
if example.has_been_called: 
    print("foo bar") 

你也可以使用一個裝飾設置屬性:

import functools 

def trackcalls(func): 
    @functools.wraps(func) 
    def wrapper(*args, **kwargs): 
     wrapper.has_been_called = True 
     return func(*args, **kwargs) 
    wrapper.has_been_called = False 
    return wrapper 

@trackcalls 
def example(): 
    pass 


example() 

#Actual Code!: 
if example.has_been_called: 
    print("foo bar") 
+0

有趣的是知道該函數可以獲得一個屬性,因爲Python中的所有東西都是一個對象。函數是「函數」類的對象。而且你可以爲一個實例指定一個屬性,因爲你不必在Python中聲明變量,所以你可以在運行時分配它們。 – 2014-08-08 14:46:39

0

這裏有一個裝飾者,將使用colorama來觀看你所有的功能,以獲得一個不錯的輸出。

嘗試: 進口coloramac 除了導入錯誤: 類一個StdClass:通過 DEF過路人(*指定參數時,** kwargs):通過 COLORAMA =一個StdClass() colorama.init =過路人 colorama.Fore =一個StdClass( ) colorama.Fore.RED = colorama.Fore.GREEN = ''

def check_for_use(show=False): 
    if show: 
     try: 
      check_for_use.functions 
     except AttributeError: 
      return 
     no_error = True 
     for function in check_for_use.functions.keys(): 
      if check_for_use.functions[function][0] is False: 
       print(colorama.Fore.RED + 'The function {!r} hasn\'t been called. Defined in "{}" '.format(function, check_for_use.functions[function][1].__code__.co_filename)) 
       no_error = False 
     if no_error: 
      print(colorama.Fore.GREEN + 'Great! All your checked function are being called!') 
     return check_for_use.functions 
    try: 
     check_for_use.functions 
    except AttributeError: 
     check_for_use.functions = {} 
     if colorama: 
      colorama.init(autoreset=True) 

    def add(function): 
     check_for_use.functions[function.__name__] = [False, function] 
     def func(*args, **kwargs): 
      check_for_use.functions[function.__name__] = [True, function] 
      function(*args, **kwargs) 
     return func 
    return add 

@check_for_use() 
def hello(): 
    print('Hello world!') 

@check_for_use() 
def bonjour(nb): 
    print('Bonjour tout le monde!') 


# hello(); bonjour(0) 

hello() 


check_for_use(True) # outputs the following 
輸出:
Hello world! 
The function 'bonjour' hasn't been called. Defined in "path_to_file.py"