0

我创建了一个 Python 类,它的核心有一个重要的浮点值,它的所有方法都在其中工作。让它与算术运算符一起运行会非常方便,例如:

i = MyClass(2.42342)
j = i + 5.2329

如果我__add__(self, other)为类创建一个方法,我会实现这一点,如下所示:

def __add__(self, other):
    return float(other) + self.number

def __float__(self):
    return float(self.number)

这样我可以添加我的类的 2 个实例,返回一个浮点数,我可以向一个实例添加一个浮点数。但是如果浮动在左侧,我会得到一个错误,使加法不可交换:

i = MyClass(3.2127)
i + 1.6743
# returns 4.887
1.6743 + i
# TypeError: unsupported operand type(s) for +: 'float' and 'instance'

我的问题是,如何让 Python 知道我的类是一种适合作为浮点数的类型?在许多模块中,我们可以看到不是浮点类型但行为类似于浮点的对象。举例来说,numpy 有自己的类型,比如numpy.float64,它不是 Python <type 'float'>,但 Python 知道+该对象支持操作数和其他类型:

import numpy
i = numpy.float64(12.745)
type(i)
# <type 'numpy.float64'>
j = 4.232
type(j)
# <type 'float'>
j + i
# 16.977

如果您想尝试,这是清理过的课程:

class MyClass(object):

    def __init__(self, number):
        self.number = number

    def __neg__(self):
        return -1 * self.number

    def __add__(self, other):
        return float(other) + self.number

    def __sub__(self, other):
        return self.number - float(other)

    def __mul__(self, other):
        return self.number * float(other)

    def __float__(self):
        return self.number
4

0 回答 0