将Python内置类型替换为自定义类型 [英] Replace Pythons builtin type with custom one

查看:117
本文介绍了将Python内置类型替换为自定义类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以用自定义类型替换某些内置python类型?

Is it possible to replace some built-in python types with custom ones?

我想创建类似以下内容的东西:

I want to create something like:

class MyInt(object):
   ...
__builtin__.int = MyInt
x = 5


推荐答案

由于要编写Pythonesque DSL,因此有两个选择:

Since you want to write a Pythonesque DSL, you have two options:


  1. 将代码编译为AST,并根据需要遍历AST替换节点。

  2. 用手构建自己的AST。

一旦有了AST,就可以直接执行它。无论哪种情况,请查看 Python的语言服务,以生成和操作AST。

Once you have the AST you can go ahead and execute it directly. In either case, look at Python's Language Services for generation and manipulation of the AST.

这篇关于将Python内置类型替换为自定义类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆