From eebdbfe679237a3efb0ec1605d9e41e875dbd5c1 Mon Sep 17 00:00:00 2001 From: Nicolas Trinquier Date: Sun, 28 Apr 2019 22:57:56 +0200 Subject: [PATCH] Add int and float methods for the complex type --- tests/snippets/builtin_complex.py | 2 +- vm/src/obj/objcomplex.rs | 14 ++++++++++++-- 2 files changed, 13 insertions(+), 3 deletions(-) diff --git a/tests/snippets/builtin_complex.py b/tests/snippets/builtin_complex.py index 9c13e2d85..4d0fa1202 100644 --- a/tests/snippets/builtin_complex.py +++ b/tests/snippets/builtin_complex.py @@ -26,7 +26,7 @@ assert complex(1, 2).__eq__('foo') == NotImplemented # __mul__ -assert complex(2, -3) * complex(-5, 7) == complex(-21, 29) +assert complex(2, -3) * complex(-5, 7) == complex(11, 29) assert complex(2, -3) * 5 == complex(10, -15) # __neg__ diff --git a/vm/src/obj/objcomplex.rs b/vm/src/obj/objcomplex.rs index 3dd48c3f9..cd70c61c7 100644 --- a/vm/src/obj/objcomplex.rs +++ b/vm/src/obj/objcomplex.rs @@ -161,12 +161,22 @@ impl PyComplex { vm.ctx.new_bool(result) } + #[pymethod(name = "__float__")] + fn float(&self, vm: &VirtualMachine) -> PyResult { + return Err(vm.new_type_error(String::from("Can't convert complex to float"))); + } + + #[pymethod(name = "__int__")] + fn int(&self, vm: &VirtualMachine) -> PyResult { + return Err(vm.new_type_error(String::from("Can't convert complex to int"))); + } + #[pymethod(name = "__mul__")] - fn mul(self, other: PyObjectRef, vm: &VirtualMachine) -> PyObjectRef { + fn mul(&self, other: PyObjectRef, vm: &VirtualMachine) -> PyResult { match to_complex(other, vm) { Ok(Some(other)) => Ok(vm.ctx.new_complex(Complex64::new( self.value.re * other.re - self.value.im * other.im, - self.value.re * other.im + self.value.re * other.im, + self.value.re * other.im + self.value.im * other.re, ))), Ok(None) => Ok(vm.ctx.not_implemented()), Err(err) => Err(err),