繁体   English   中英

Python变量作用域的两个功能

[英]Python variable scoping of two functions

我试图搜索该问题,但找不到实际答案。 我正在尝试实现一个函数(magic_debug),以便在另一个函数(somefunc)中调用时,它可以访问somefunc中的变量,并按如下所示打印出来:

def magic_debug(s, *args, **kwargs):
    s2 = s.format(x=x,y=y,z=args[0])
    print(s2)


def somefunc():
    x = 123
    y = ['a', 'b']
    magic_debug('The value of x is {x}, and the list is {y} of len {z}', len(y))

somefunc()

预期的输出-> x的值为123,列表为len 2的['a','b']

这确实是一个常见问题,请尝试使用inspect

def magic_debug(s, *args, **kwargs):
    import inspect
    parent_local_scope = inspect.currentframe().f_back.f_locals
    s2 = s.format(**parent_local_scope, z=args[0])
    print(s2)


def somefunc():
    x = 123
    y = ['a', 'b']
    magic_debug('The value of x is {x}, and the list is {y} of len {z}', len(y))

somefunc()

输出:

The value of x is 123, and the list is ['a', 'b'] of len 2

你是真的吗

def magic_debug(s, vars_dict):

    s2 = s.format(**vars_dict)
    print(s2)


def somefunc():
   x = 123         # variables are indent in python
   y = ['a', 'b']  # so they're in the function scope

                   # and so is this function that somefunc calls - 
   vars_dict = vars()
   vars_dict['z'] = len(y)
   magic_debug('The value of x is {x}, and the list is {y} of len {z}', vars_dict)

somefunc()

试试看-您需要缩进功能

def magic_debug(s, *args, **kwargs):

    s2 = s.format(x=x,y=y,z=args[0])
    print(s2)


def somefunc():
   x = 123         # variables are indent in python
   y = ['a', 'b']  # so they're in the function scope

                   # and so is this function that somefunc calls - 
   magic_debug('The value of x is {x}, and the list is {y} of len {z}', len(y))

somefunc()

更改一些代码,使其看起来像这样:

def magic_debug(s, *args, **kwargs):
    s2 = s.format(x=args[1],y=kwargs.pop('y', ''),z=args[0])
    print(s2)


def somefunc():
    x = 123
    y = ['a', 'b']
    magic_debug('The value of x is {x}, and the list is {y} of len {z}', len(y), x, y=y)

somefunc()

您的输出将是完美的。 您要添加** Kargs,但不使用它。 上面的代码使用** Karg存储数组。

输出:

The value of x is 123, and the list is ['a', 'b'] of len 2

编辑较少的参数:

def magic_debug(s, *args, **kwargs):
    s2 = s.format(x=args[1],y=args[0],z=len(args[0]))
    print(s2)


def somefunc():
    x = 123
    y = ['a', 'b']
    magic_debug('The value of x is {x}, and the list is {y} of len {z}', y, x)

somefunc()

如果您只要保留问题的实质就可以进行任何修改,则可以使用locals()将本地范围传递给magic_debug函数,即:

def magic_debug(s, *args, **kwargs):
    s2 = s.format(z=args[0], **kwargs)
    print(s2)

def somefunc():
    x = 123
    y = ['a', 'b']
    magic_debug('The value of x is {x}, and the list is {y} of len {z}', len(y), **locals())

somefunc()
# The value of x is 123, and the list is ['a', 'b'] of len 2

而且,如果允许您更改函数签名,则也可以不扩展而传递locals() 但是,如果您无法更改要调试的功能,则只能查看前一帧。 @Sraw已经在他的回答中提到

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM