在Python中访问基类原始类型
我想从Python的一个基本类型,浮点数(float),派生出一个新类,目的是在打印的时候显示不同的字符串。
我该如何在这个新类中访问底层的数据呢?
下面是我想做的一个简单示例:
class efloat(float):
def __repr__(self):
return "here's my number: %s" % str(WHAT CAN I PUT HERE???)
好的,谢谢大家!我想我明白了。这里是我完成的类,供有兴趣的人参考:
import math
class efloat(float):
"""efloat(x) -> floating point number with engineering representation when printed
Convert a string or a number to a floating point number, if possible.
When asked to render itself for printing (via str() or print) it is normalized
to engineering style notation at powers of 10 in multiples of 3
(for micro, milli, kilo, mega, giga, etc.)
"""
def _exponent(self):
if self == 0.0:
ret = 0
else:
ret = math.floor(math.log10(abs(self)))
return ret
def _mantissa(self):
return self/math.pow(10, self._exponent())
def _asEng(self):
shift = self._exponent() % 3
retval = "%3.12ge%+d" % (self._mantissa()*math.pow(10, shift), self._exponent() - shift)
return retval
def __str__(self):
return self._asEng()
def __repr__(self):
return str(self)
def __add__(self, x):
return efloat(float.__add__(self, float(x)))
def __radd__(self, x):
return efloat(float.__add__(self, float(x)))
def __mul__(self, x):
return efloat(float.__mul__(self, float(x)))
def __rmul__(self, x):
return efloat(float.__mul__(self, float(x)))
def __sub__(self, x):
return efloat(float.__sub__(self, float(x)))
def __rsub__(self, x):
return efloat(float.__rsub__(self, float(x)))
def __div__(self, x):
return efloat(float.__div__(self, float(x)))
def __rdiv__(self, x):
return efloat(float.__rdiv__(self, float(x)))
def __truediv__(self, x):
return efloat(float.__truediv__(self, float(x)))
def __rtruediv__(self, x):
return efloat(float.__rtruediv__(self, float(x)))
def __pow__(self, x):
return efloat(float.__pow__(self, float(x)))
def __rpow__(self, x):
return efloat(float.__rpow__(self, float(x)))
def __divmod__(self, x):
return efloat(float.__divmod__(self, float(x)))
def __neg__(self):
return efloat(float.__neg__(self))
def __floordiv__(self, x):
return efloat(float.__floordiv__(self, float(x)))
2 个回答
2
你可以通过访问基类的方法来调用它们,这样可以得到一个未绑定的方法,然后用self来调用它们:
class myfloat(float):
def __str__(self):
return "My float is " + float.__str__(self)
print(myfloat(4.5))
4
如果你没有重写 __str__
这个方法,它仍然会使用底层的方法,所以:
class efloat(float):
def __repr__(self):
return "here's my number: %s" % self
这样是可以正常工作的。更一般来说,你可以使用 self+0
、self*1
,或者其他任何你没有特别重写的操作;如果你把这些都重写了,最坏的情况就是用 float.__add__(self, 0)
之类的方法。