0

コアに 1 つの重要な float 値を持つ 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 つのインスタンスを追加して float を返すことができ、1 つのインスタンスに float を追加することができます。しかし、フロートが左側にある場合、エラーが発生し、加算が可換ではなくなります。

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

私の質問は、私のクラスが float として動作するのに適した型であることを Python に認識させるにはどうすればよいですか? 多くのモジュールでは、float 型ではなく、float のように動作するオブジェクトを見ることができます。たとえば、 numpy にはnumpy.float64、 Python ではないなどの独自の型がありますが、Pythonは、このオブジェクトで<type 'float'>オペランドやその他がサポートされていることを認識しています。+

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