python - 如何覆盖像 round() 这样的默认 python 函数?

标签 python python-3.x python-2.x

我想覆盖 python 的默认 round() 函数,因为我必须将 round() 函数的结果转换为整数。默认情况下 round() 返回浮点值。 下面给出的代码返回错误消息。

运行时错误:调用 Python 对象时超出最大递归深度。

def round(number):
     if type(number) is float: return int(round(number))
     return None

最佳答案

当前代码的问题是,在覆盖内置的 round() 方法后,当您在自己的 中调用 round() 时round() ,您正在递归调用您自己的函数,而不是内置的 round 函数。

对于 Python 3.x,您可以使用 builtins访问 round() 内置函数的模块 -

import builtins
def round(number):
    if type(number) is float: return int(builtins.round(number))
    return None

对于 Python 2.x,它将是 __builtin__模块 -

import __builtin__
def round(number):
    if type(number) is float: return int(__builtin__.round(number))
    return None

虽然我真的建议不要这样做,而是为你的 round 函数使用一个新名称,比如 round_int 之类的。

请注意,另一件事是您的代码将返回 float 类型的舍入数字,对于所有其他类型,它将返回 None ,我不确定是否这是有意还是无意,但我猜你会想要返回其他类型的 number(至少 int?)。

关于python - 如何覆盖像 round() 这样的默认 python 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32822046/

相关文章:

Python - 停止长时间运行的taskq线程

python - 尝试访问 gandi api 时出现 xmlrpclib 错误 'module not found'

python : Using Decorators to write Logs on a file

python - "No module named abc_base"

python - 为什么在 Python 中 `50 << 6` 为真,而 `50 >> 6` 为假?

Python 在冒号后声明一个名称的类的奇怪方式

python - 确定时间范围内可用的最小用户数

python - 如何在 python 中运行非线性回归

python - 将 self.__class__ 设置为其他东西有多危险?

python - raw_input 在请求输入后打印提示