发表自己的言论
有没有办法在 Python 中定义我自己的新语句,例如 def
、with
、for
?当然,我并不是要覆盖现有的语句,只是创建一些我自己的语句。
如果是这样,我该怎么做?您能给我指出有关该主题的优秀文档吗?
Is there a way to define new statements like def
, with
, for
of my own in Python? Of course, I don't mean to override the existing statements, only create some of my own.
If so, how do I do it? Can you point me to good docs on the subject?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
不可以,您不能在 Python 程序中添加新语法。改变语言的唯一方法是编辑和重新编译语法文件和支持的C代码,以获得新的改变的解释器、编译器和运行时。
No, you cannot add new syntax within a Python program. The only way to alter the language is to edit and recompile the grammar file and supporting C code, to obtain a new altered interpreter, compiler and runtime.
如果不重写编译器/解释器等,您就无法(重新)定义语言关键字。您可能可以做的是编写类似 DSL(特定于域的语言)之类的东西,以及将关键字语句转换为正确的 python 语句的东西,这可能是一条更简单的路线。
You can't (re)define language keywords without rewriting a compiler/interpreter/etc. What you could do perhaps is write a something like a DSL (domain-specific language) and something that translates your keyword statements into proper python statements, which might be an easier route.
虽然您无法修改 Python 本身的语法(无需像 Alex 提到的那样重新编译),但您可以使用元编程技术。下面是有关使用 Python 创建 DSL 的演示文稿的链接。
http://blog.brianbeck.com/post/53538107/python-dsl- i
如果您没有使用 Python,那么 Ruby 是定义 DSL 的绝佳语言,因为它具有更广泛的元编程功能。
http://www. themorohoax.com/2009/02/25/how-to-write-a-clean-ruby-dsl-rails
While you can't modify the syntax of Python itself (without recompiling as Alex has mentioned), you can use metaprogramming techniques. Below is a link to a presentation on creating a DSL in Python.
http://blog.brianbeck.com/post/53538107/python-dsl-i
If you're not married to Python, Ruby is a great language for defining DSL's, as it has broader metaprogramming capabilities.
http://www.themomorohoax.com/2009/02/25/how-to-write-a-clean-ruby-dsl-rails
Ren'Py 是 Python 扩展的一个示例,它允许通过实现自己的解析器和编译器来自定义语句。
Ren'Py is an example of an extension for Python that allows custom statements by implementing its own parser and compiler.
有一些编程语言可以让您执行此操作(例如 Tcl),但 Python 不是其中之一。
There are programming languages that let you do this (Tcl, for example), but Python isn't one of those languages.