动态名称解析
PHP 和 Python 等某些语言为何使用动态名称解析?
我唯一一次想到使用它是做类似这个 Python 代码的事情,这样我就不必显式地将参数设置为 format
:
"{a} {b} {c} {d}".format(**locals())
但实际上并不需要太多工作就可以了显式(并且不太容易出错):
"{a} {b} {c} {d}".format(a=a, b=b, c=c, d=d)
为了在同一范围内设置/获取局部变量,我不明白为什么有人会使用它而不是地图。
如果没有动态名称解析,拼写错误就会被捕获,并且您可以自动重命名变量而不会破坏程序(除非某些东西仍然可以读取变量的名称)。通过动态名称解析,您可以获得一些可以让您免于键入一行的东西吗?我错过了什么吗?
Python 文档称他们将来可能会删除它。是不是更具有历史意义?动态名称解析的实际良好用例是什么?
Howcome some languages like PHP and Python use dynamic name resolution?
The only time I've ever thought of using it is to do something like this Python code, to save me from having to explicitly parameters to format
:
"{a} {b} {c} {d}".format(**locals())
but it doesn't really take much work to just be explicit (and is a bit less error-prone):
"{a} {b} {c} {d}".format(a=a, b=b, c=c, d=d)
And for setting/getting locals in the same scope, I don't see why anyone would ever use that instead of a map.
Without dynamic name resolution, typos are caught, and you can automatically rename variables without breaking your program (unless something can still read the names of the variables). With dynamic name resolution, you get something that saves you from typing a line? Am I missing something?
Python documentation says they might remove it in the future. Is it more of a historical thing? What's an actual good use case for dynamic name resolution?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
大多数动态类型语言根本没有选择。对于像
xy
这样的表达式,您无法静态查找y
,因为哪些字段可用取决于仅可用的x
的类型在运行时。有很多方法可以解决这个问题(例如类型推断或 JIT),但由于基本语言必须具有动态名称查找功能,因此大多数此类语言将其纳入功能(例如参见 Lua 表的强大功能) 。
Most dynamically typed languages simply don't have a choice. For an expression like
x.y
you can't look upy
statically, since what fields are available depends on the type ofx
which is only available at runtime.There are ways around this (such as type inference or JIT), but since the base language has to have dynamic name lookup, most such languages make it into a feature (see e.g. the power of Lua tables).