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的__init__方法接收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的__init__方法。

当然,更好的方法是使用property装饰器。 

原文地址:https://www.cnblogs.com/blackmatrix/p/5604160.html