Python的locals()函数

Posted BlackMatrix

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python的locals()函数相关的知识,希望对你有一定的参考价值。

Python的locals()函数会以dict类型返回当前位置的全部局部变量。

示例代码:

def func():
    arg_a, arg_b = a, b

    def func_a():
        pass

    def func_b():
        pass

    def print_value():
        print(arg_a, arg_b)

    return locals()


if __name__ == __main__:

    args = func()
    print(type(args))
    print(args)

运行结果可以看出,会将函数func的局部变量以dict类型返回。

<class dict>
{func_a: <function func.<locals>.func_a at 0x10d8f71e0>, arg_b: b, arg_a: a, print_value: <function func.<locals>.print_value at 0x10d8f7378>, func_b: <function func.<locals>.func_b at 0x10d8f72f0>}

将locals()与property结合提高代码可读性

class NewProps(object):

    def __init__(self):
        self._age = 40

    def fage():
        doc = "The age property."

        def fset(self, value):
            self._age = int(value)

        def fget(self):
            return self._age

        def fdel(self):
            del self._age

        return locals()

    age = property(**fage())

if __name__ == __main__:
    x = NewProps()
    print(x.age)
    x.age = 50
    print(x.age)

这里需要注意的是fage()方法下4个属性名称不能修改(也不能新增其他属性,除非对locals()返回的dict进行处理,移除多余的元素),必须为fset、fget、fdel、doc,如果修改属性名称,会抛出如下异常:

f_set is an invalid keyword argument for this function

因为,property方法接收4个参数(self除外,因为Python编译器会自动把self传入)

def __init__(self, fget=None, fset=None, fdel=None, doc=None): # known special case of property.__init__
  .....

在return locals()时,返回dict,key的值和参数的name一一对应,以**kwargs参数的形式传入函数property。

 

以上是关于Python的locals()函数的主要内容,如果未能解决你的问题,请参考以下文章

Python标准库 内置函数eval expression globals None locals None

[py]Python locals() 函数

Python内置函数(39)——locals

Python 内置函数 locals() 和globals()

Python globals和locals函数_reload函数

python 中locals() 和 globals()