我正在尝试从python原语派生一个类,即浮点数,以便在打印出来时打印不同的repr字符串。
当我这样做时,如何从派生类访问基础数据?
以下是我想要做的简化示例:
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)))
答案 0 :(得分:4)
如果你没有覆盖__str__
,那仍然会访问基础方法,所以:
class efloat(float):
def __repr__(self):
return "here's my number: %s" % self
会奏效。更一般地说,您可以使用self+0
,self*1
或任何其他未明确覆盖的身份操作;如果你将它们全部覆盖,最糟糕的情况是float.__add__(self, 0)
或类似情况。
答案 1 :(得分:2)
您可以调用基类方法,通过从基类访问它们来获取未绑定的方法并使用self调用它们:
class myfloat(float):
def __str__(self):
return "My float is " + float.__str__(self)
print(myfloat(4.5))