Fraction: Python operators, formatter

- Equivalents of operator* and operator/ templates are provided
  by implemening `__mul__`, `__rmul__`, __truediv__`, `__rtruediv__`
  in Python code for `openshot.Fraction` class
- An implementation of `__format__` is also provided, allowing
  numeric format strings to be used directly on Fraction objects,
  e.g. `v = Fraction(3, 9); print(f"{v:0.3f}")  # prints '0.333'`
This commit is contained in:
FeRD (Frank Dana)
2021-10-31 07:52:12 -04:00
parent 1af4d0f8cf
commit 397db7ba31

View File

@@ -209,6 +209,31 @@
def values(self):
_items = self.GetMap()
return _items.values()
def __mul__(self, other):
if isinstance(other, Fraction):
return Fraction(self.num * other.num, self.den * other.den)
return float(self) * other
def __rmul__(self, other):
return other * float(self)
def __truediv__(self, other):
if isinstance(other, Fraction):
return Fraction(self.num * other.den, self.den * other.num)
return float(self) / other;
def __rtruediv__(self, other):
return other / float(self)
def __format__(self, format_spec):
integer_fmt = "bcdoxX"
float_fmt = "eEfFgGn%"
all_fmt = "".join(["s", integer_fmt, float_fmt])
if not format_spec or format_spec[-1] not in all_fmt:
value = str(self)
elif format_spec[-1] in integer_fmt:
value = int(self)
elif format_spec[-1] in float_fmt:
value = float(self)
else:
value = str(self)
return "{value:{spec}}".format(value=value, spec=format_spec)
%}
}