Python的locals()函数
Python 函数
2023-09-27 14:21:29 时间
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装饰器。
相关文章
- python学习笔记(正则表达式)
- python基础之字符串、函数、BUG和异常类型介绍及类和对象详细笔记
- 每日测试冷知识:Python函数(方法)
- Python基础内置函数及用法解析
- Python面试题之Python的Super方法
- python: 模块发布
- python函数 传参的多种方式 解读
- python 内置函数
- python 局部变量和全局变量 global
- Python老王视频习题答案
- 第11.22节 Python 中re模块的字符串分割器:split函数
- 被老猿误解的Python匿名函数lambda
- python编程(数据库操作)
- python 读取Excel(二)之xlwt
- Python numpy.std函数方法的使用
- Python numpy.asanyarray函数方法的使用
- Python pandas.DataFrame.rolling函数方法的使用
- Python pandas.DataFrame.lt函数方法的使用
- Python pandas.DataFrame.hist函数方法的使用
- Python pandas.DataFrame.get_values函数方法的使用
- Python pandas.DataFrame.xs函数方法的使用
- Python Pandas pandas.read_sql_query函数方法的使用
- Python numpy.full函数方法的使用
- Python 使用和高性能技巧总结
- 三维点云重建 — open3d python
- python实现 字符串匹配函数
- python jsonpath 模块的应用
- python:打印直角三角形