Replace Pythons builtin type with custom one

不羁的心 提交于 2019-12-07 11:06:58

问题


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

回答1:


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

  1. Compile the code to an AST and walk the AST replacing nodes as appropriate.
  2. Build your own AST by hand.

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.




回答2:


You seem to be asking if it's possible to override the type that is created when you enter literals. The answer is no. You cannot make it so that x = 5 uses a type other than the built-in int type.

You can override __builtin__.int, but that will only affect explicit use of the name int, e.g., when you do int("5"). There's little point to doing this; it's better to just use your regular class and do MyInt("5").

More importantly, you can provide operator overloading on your classes so that, for instance, MyInt(5) + 5 works and returns another MyInt. You'd do this by writing an __add__ method for your MyInt class (along with __sub__ for subtraction, etc.).




回答3:


I don't know about replacing the built-ins, but you can certainly create an object that inherits from them, and/or behaves like them. Look up something like inherit from immutable and you should find answers that show overriding of __new__, or for the latter option see 'Emulating Numeric Types'



来源:https://stackoverflow.com/questions/11787922/replace-pythons-builtin-type-with-custom-one

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!