为什么不能为非浮点定义`round`? [英] Why can't `round` be defined for non-floats?

查看:140
本文介绍了为什么不能为非浮点定义`round`?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定一个简单的类如

class Vector(object):
    def __init__(self, value):
        self.value = value
    def __abs__(self):
        return math.sqrt(sum([x**2 for x in self.value]))
    def __round__(self, *n):
        return [round(x,*n) for x in self.value]


b $ b

为什么 abs(Vector([ - 3,4]))正确产生 5 while round(Vector([ - 3.1,4]))抱怨一个 TypeError:float是必需的 [ - 3,4] ,如何解决?

why does abs(Vector([-3,4])) correctly yield 5 while round(Vector([-3.1,4])) complains with a TypeError: a float is required instead of the desired [-3,4], and how can this be fixed?

我知道 round 通常应该返回一个浮点数,但对于一个向量,在这个例子中可能没有歧义的可能的意义,所以为什么这不能简单地覆盖?我真的需要子类 numbers.Real ,或者定义 Vector(...)。round(n)

I know round should usually return a float, but for a vector as in this example there is probably no ambiguity on the possible meaning, so why can this not be simply overridden? Do I really have to subclass numbers.Real, or define Vector(...).round(n) instead?

推荐答案

__ round __ 特殊方法仅在Python 3中引入。在Python 2中不支持特殊方法。

The __round__ special method was only introduced in Python 3. There is no support for the special method in Python 2.

您必须使用专用方法,而不是使用函数:

You'll have to use a dedicated method instead of the function:

class Vector(object):
    def __init__(self, value):
        self.value = value

    def round(self, n):
        return [round(x, n) for x in self.value]


b $ b

或者你必须提供自己的 round()函数:

import __builtin__

def round(number, digits=0):
    try:
        return number.__round__(digits)
    except AttributeError:
        return __builtin__.round(number, digits)

__ builtins __ 命名空间:

import __builtin__

_bltin_round = __builtin__.round

def round(number, digits=0):
    try:
        hook = number.__round__
    except AttributeError:
        return _bltin_round(number, digits)
    else:
        # Call hook outside the exception handler so an AttributeError 
        # thrown by its implementation is not masked
        return hook(digits)

__builtin__.round = round

这篇关于为什么不能为非浮点定义`round`?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆