Sub-classing a built-in Python type such as int

╄→гoц情女王★ 提交于 2019-12-12 01:24:40

问题


I tried sub-classing the built-in int object along the lines of this example but I got a strange error.

Here is the code and resulting Traceback.

# Built-in namespace
import __builtin__

# Extended subclass
class myint(int):
    def in_words(self):
        if self:
            return 'one million'
        else:
            return ''

# Substitute the original int with the subclass on the built-in namespace    
__builtin__.int = myint

(I was planning to write a method to return an integer as a series of words like on a cheque).

Just executing this definition code causes the following:

Traceback (most recent call last):

  File "/Users/billtubbs/anaconda/lib/python2.7/site-packages/ipykernel/ipkernel.py", line 175, in do_execute
    shell.run_cell(code, store_history=store_history, silent=silent)

  File "/Users/billtubbs/anaconda/lib/python2.7/site-packages/IPython/core/interactiveshell.py", line 2917, in run_cell
    self.execution_count += 1

  File "/Users/billtubbs/anaconda/lib/python2.7/site-packages/traitlets/traitlets.py", line 450, in __set__
    new_value = self._validate(obj, value)

  File "/Users/billtubbs/anaconda/lib/python2.7/site-packages/traitlets/traitlets.py", line 471, in _validate
    value = self.validate(obj, value)

  File "/Users/billtubbs/anaconda/lib/python2.7/site-packages/traitlets/traitlets.py", line 1266, in validate
    self.error(obj, value)

  File "/Users/billtubbs/anaconda/lib/python2.7/site-packages/traitlets/traitlets.py", line 499, in error
    raise TraitError(e)

TraitError: The 'execution_count' trait of a ZMQInteractiveShell instance must be an integer, but a value of 2 <type 'int'> was specified.

回答1:


You can subclass a builtin type, the problem comes with you try to replace a built-in type. This is a chicken and egg problem.

As a golden rule, never replace builtins. If you never want to use an int again in YOUR PROGRAM, then do int = myint and call it good. Don't touch __builtin__.int

The specific error here is IPython doing some validation and checking if type(foo) is int, which fails. If they'd done isinstance(foo, int) it would have succeeded. Be a conscientious coder -- don't muck with the internals that other modules are using.



来源:https://stackoverflow.com/questions/34032765/sub-classing-a-built-in-python-type-such-as-int

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