【问题标题】:Sub-classing a built-in Python type such as int子类化一个内置的 Python 类型,例如 int
【发布时间】:2015-12-02 00:20:13
【问题描述】:

我尝试按照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.

【问题讨论】:

    标签: python class object inheritance methods


    【解决方案1】:

    你可以继承一个内置类型,问题是你尝试替换一个内置类型。这是先有鸡还是先有蛋的问题。

    作为黄金法则,永远不要替换内置函数。如果您不想在您的程序中再次使用int,请执行int = myint 并称其为好。不要碰__builtin__.int

    这里的具体错误是 IPython 进行了一些验证并检查 type(foo) is int 是否失败。如果他们完成了isinstance(foo, int),它就会成功。做一个尽职尽责的程序员——不要搞砸其他模块正在使用的内部结构。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-07-08
      • 1970-01-01
      • 2011-06-17
      • 2011-09-14
      • 2021-05-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多