簡體   English   中英

如何對存儲在變量中的函數使用 repr() 來檢索其源代碼?

[英]How to use repr() for functions stored in variables to retrieve their source code?

我希望能夠在 python 中的一個類上執行repr() ,該類的函數存儲在類的變量中,以便稍后在eval()表示輸出時重現相同的函數。

這是一個示例來說明我的問題:

class Example:
    def __init__(self, func):
        self.func = func

    def __repr__(self):
        return repr(self.func)


def add(x, y):
    return x + y


example = Example(add)
print(repr(example))

當我運行該代碼時,我得到的輸出是:

<function add at 0x7f6ea0e96e18>

有沒有辦法制作一個repr() ,它會輸出一些東西,然后可以eval() ed 到一個可調用的函數。 理想情況下,我想要這樣的輸出:

def add(x, y): return x + y

您可以使用 Python 的inspect模塊來做到這一點:

import inspect


class Example:
    def __init__(self, func):
        self.func = func

    def __repr__(self):
        return inspect.getsource(self.func)


def add(x, y):
    return x + y


example = Example(add)
print(repr(example))

輸出:

def add(x, y):
    return x + y

暫無
暫無

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

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