財務計算を行うためにPythonプログラムでDecimalクラスを使用したいと思います。floatで機能しない小数-最初に文字列に明示的に変換する必要があります。そこで、明示的な変換なしでfloatを操作できるように、Decimalをサブクラス化することにしました。
m_Decimal.py:
# -*- coding: utf-8 -*-
import decimal
Decimal = decimal.Decimal
def floatCheck ( obj ) : # usually Decimal does not work with floats
return repr ( obj ) if isinstance ( obj, float ) else obj # this automatically converts floats to Decimal
class m_Decimal ( Decimal ) :
__integral = Decimal ( 1 )
def __new__ ( cls, value = 0 ) :
return Decimal.__new__ ( cls, floatCheck ( value ) )
def __str__ ( self ) :
return str ( self.quantize ( self.__integral ) if self == self.to_integral () else self.normalize () ) # http://docs.python.org/library/decimal.html#decimal-faq
def __mul__ ( self, other ) :
print (type(other))
Decimal.__mul__ ( self, other )
D = m_Decimal
print ( D(5000000)*D(2.2))
だから今、書く代わりに、私は例外を発生させることなくD(5000000)*D(2.2)
書くことができるはずです。D(5000000)*2.2
いくつか質問があります。
私の決定は私に何か問題を引き起こしますか?
他の引数はタイプであるため、の場合、再実装
__mul__
は機能しませんが、10進モジュールで次のことを確認できます。D(5000000)*D(2.2)
class '__main__.m_Decimal'
decimal.py、行5292:
def _convert_other(other, raiseit=False):
"""Convert other to Decimal.
Verifies that it's ok to use in an implicit construction.
"""
if isinstance(other, Decimal):
return other
if isinstance(other, (int, long)):
return Decimal(other)
if raiseit:
raise TypeError("Unable to convert %s to Decimal" % other)
return NotImplemented
10進モジュールは、引数がDecimalまたはintであることを想定しています。これは、m_Decimalオブジェクトを最初に文字列に変換してからDecimalに変換する必要があることを意味します。しかし、これは多くの無駄です-m_DecimalはDecimalの子孫です-これを使用してクラスを高速化するにはどうすればよいですか(Decimalはすでに非常に遅いです)。
- cDecimalが表示されるとき、このサブクラス化は機能しますか?