相关疑难解决方法(0)

从Python中调用命名空间获取本地人员

我想从被调用的函数中检索Python中的局部变量.有没有办法做到这一点?我意识到这不适合大多数编程,但我基本上构建了一个调试器.例如:

def show_locals():
  # put something in here that shows local_1.

local_1 = 123
show_locals()  # I want this to show local_1.
Run Code Online (Sandbox Code Playgroud)

我把什么放在体内show_locals?如果我必须修改调用语句,我可以进行的最小修改是什么?

注意:show_locals它与调用者位于不同的模块时,这必须起作用.

python metaprogramming

32
推荐指数
2
解决办法
7423
查看次数

你可以重载Python 3.6 f-string的"运算符"吗?

在Python 3.6中,您可以使用以下f字符串:

>>> date = datetime.date(1991, 10, 12)
>>> f'{date} was on a {date:%A}'
'1991-10-12 was on a Saturday'
Run Code Online (Sandbox Code Playgroud)

我想重载接收'%A'上述方法的方法.可以吗?

例如,如果我想写一个愚蠢的包装器datetime,我可能期望这个重载看起来像:

class MyDatetime:
    def __init__(self, my_datetime, some_other_value):
        self.dt = my_datetime
        self.some_other_value = some_other_value

    def __fstr__(self, format_str):
        return (
            self.dt.strftime(format_str) + 
            'some other string' +
            str(self.some_other_value
        )
Run Code Online (Sandbox Code Playgroud)

python python-3.x python-3.6 f-string

12
推荐指数
1
解决办法
653
查看次数