From 397db7ba31720286cb747e72ab0c4fa838daec5e Mon Sep 17 00:00:00 2001 From: "FeRD (Frank Dana)" Date: Sun, 31 Oct 2021 07:52:12 -0400 Subject: [PATCH] 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'` --- bindings/python/openshot.i | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/bindings/python/openshot.i b/bindings/python/openshot.i index 20990b2c..1ee7340b 100644 --- a/bindings/python/openshot.i +++ b/bindings/python/openshot.i @@ -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) %} }