2017-05-08 79 views
0

我要撰寫關於喜歡什麼參數給定函數獲取給定的信息等等。我想這樣做的例子是裝飾:保持狀態

@author("Joey") 
@parameter("name", type=str) 
@parameter("id", type=int) 
@returns("Employee", desc="Returns employee with given details", type="Employee") 
def get_employee(name, id): 
    // 
    // Some logic to return employee 
    // 

骷髏裝飾的可能如下:

json = {} 
def author(author): 
    def wrapper(func): 
     def internal(*args, **kwargs): 
       json["author"] = name 
       func(args, kwargs) 
     return internal 
    return wrapepr 

類似地,參數裝飾可以寫成如下:

def parameter(name, type=None): 
    def wrapper(func): 
     def internal(*args, **kwargs): 
       para = {} 
       para["name"] = name 
       para["type"] = type 
       json["parameters"].append = para 
       func(args, kwargs) 
     return internal 
    return wrapepr 

同樣,可以編寫其他處理程序。最後,我可以調用一個函數來爲每個函數獲取所有形成的JSON。

末輸出可以

[ 
{fun_name, "get_employee", author: "Joey", parameters : [{para_name : Name, type: str}, ... ], returns: {type: Employee, desc: "..."} 
{fun_name, "search_employee", author: "Bob", parameters : [{para_name : age, type: int}, ... ], returns: {type: Employee, desc: "..."} 
... 
} 
] 

我不知道我怎麼能保持狀態,並瞭解鞏固有關一個功能應一起處理數據。

我該如何做到這一點?

回答

0

我不知道如果我完全得到你的使用情況,但不會是工作,筆者添加到您當前的功能:

func_list = [] 

def func(var): 
    return var 

json = {} 
json['author'] = 'JohanL' 
json['func'] = func.func_name 
func.json = json 

func_list.append(func.json) 

def func2(var): 
    return var 

json = {} 
json['author'] = 'Ganesh' 
func2.json = json 

func_list.append(func2.json) 

這可以使用裝飾如下自動化:

def author(author): 
    json = {} 
    def author_decorator(func): 
     json['func'] = func.func_name 
     json['author'] = author 
     func.json = json 
     return func 
    return author_decorator 

def append(func_list): 
    def append_decorator(func): 
     func_list.append(func.json) 
     return func 
    return append_decorator 

func_list = [] 

@append(func_list) 
@author('JohanL') 
def func(var): 
    return var 

@append(func_list) 
@author('Ganesh') 
def func2(var): 
    return var 

然後你就可以訪問json字典爲func.jsonfunc2.json或發現在func_list的功能。請注意,爲了裝飾者的工作,你必須添加他們的順序,我已經把他們,我沒有添加任何錯誤處理。

而且,如果你喜歡func_list不明確的被傳遞,而是使用一個globaly定義的列表中有一個明確的名稱,代碼可以稍微簡化爲:

func_list = [] 

def author(author): 
    json = {} 
    def author_decorator(func): 
     json['func'] = func.func_name 
     json['author'] = author 
     func.json = json 
     return func 
    return author_decorator 

def append(func): 
    global func_list 
    func_list.append(func.json) 
    return func 

@append 
@author('JohanL') 
def func(var): 
    return var 

@append 
@author('Ganesh') 
def func2(var): 
    return var 

也許這是足以讓你?

+0

當作者'Ganesh'有另一個'func2'時會出現問題。我們需要創建輸出'[{func:'func',作者:'JohanL'},{func:'func2',作者:'Ganesh。}}]' 該方法是否適用於第二個函數? –

+0

這將適用於我的更新示例中顯示的兩個函數。每個人都會有一個獨特的json字典。 – JohanL

+0

感謝您的解釋@JohanL。 是的。這兩個JSON是按照JSON生成的。但最終的輸出是所有這樣的JSON的列表。爲此,我們需要創建另一個裝飾器,對吧?那個裝飾器需要在第一個裝飾器之後才被調用? –