簡體   English   中英

在另一個 function 中操縱全局 function 定義是不好的做法嗎?

[英]Is manipulating a global function definition inside another function bad practice?

我有一個名為set_func的 function,它有 25 行長。 在它里面調用update

def set_func(table: str, identifier=None, **kwargs) -> None:
    ... # does stuff with arguments
    query = update(table, kwargs, identifier)
    ...
    execute(query)

我想聲明一個名為 delete_func 的delete_func做完全相同的事情,但不是調用update而是調用delete

我的代碼:

def delete_func(table: str, identifier=None) -> None:
    global update
    backup_update = deepcopy(update)
    assert backup_update is not update

    update = delete
    try:
        return set_func(table, identifier)
    finally:
        update = backup_update

這行得通,買它似乎是不好的做法。 在不更改set_func的情況下還有另一種方法可以做到這一點嗎? 是不好的代碼嗎?

由於函數首先是 class,我可能會將要完成的任何工作作為參數傳遞到您的方法中。 或者,您可以傳入一個標志並在內部確定如何處理工作。 我絕對不會像您在這里所做的那樣更改實施,即使它在技術上可行。

我可能會這樣做:

def fn_update(table: str, identifier, **kwargs) -> None:
    # do whatever you do to just update
    return "query"

def fn_delete(table: str, identifier, **kwargs) -> None:
    # do whatever you do to just delete
    return "query"

def set_func(fn_work, table: str, identifier=None, **kwargs) -> None:
    ... # does stuff with arguments
    query = fn_work(table, identifier, kwargs)
    ...
    execute(query)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM