对内置Python类型(如int)进行子类化

时间:2015-12-02 00:20:13

标签: python class object inheritance methods

我尝试沿着this example的行对内置的int对象进行子类化,但是我遇到了一个奇怪的错误。

这是代码和结果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

(我打算写一个方法来返回一个整数作为一系列单词,比如支票)。

执行此定义代码会导致以下情况:

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 个答案:

答案 0 :(得分:2)

您可以对内置类型进行子类化,问题在于您尝试替换内置类型。这是鸡和蛋的问题。

作为一条黄金法则,永远不要取代内置的。如果您永远不想在您的计划中再次使用int,请执行int = myint并将其称为好。请勿触摸__builtin__.int

这里的具体错误是IPython做了一些验证并检查type(foo) is int是否失败。如果他们完成了isinstance(foo, int),它就会成功。做一个尽职尽责的编码员 - 不要与其他模块正在使用的内部人员混在一起。