• 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装饰器。 

     

     
  • 相关阅读:
    Oracle 删除重复数据的几种方法
    12.25模拟赛T3
    java实现第五届蓝桥杯圆周率
    java实现第五届蓝桥杯武功秘籍
    Oracle 审计初步使用
    [CERC2017]Intrinsic Interval——扫描线+转化思想+线段树
    ORA-12012 Error on auto execute of job "SYS"."ORA$AT_OS_OPT_SY_<NN> in 12.2.0 Database
    12.25模拟赛T2
    java实现第五届蓝桥杯写日志
    java实现第五届蓝桥杯李白打酒
  • 原文地址:https://www.cnblogs.com/insane-Mr-Li/p/9691358.html
Copyright © 2020-2023  润新知