Skip to content

Commit eebdbfe

Browse files
author
Nicolas Trinquier
committed
Add int and float methods for the complex type
1 parent f8373aa commit eebdbfe

File tree

2 files changed

+13
-3
lines changed

2 files changed

+13
-3
lines changed

tests/snippets/builtin_complex.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@
2626

2727
# __mul__
2828

29-
assert complex(2, -3) * complex(-5, 7) == complex(-21, 29)
29+
assert complex(2, -3) * complex(-5, 7) == complex(11, 29)
3030
assert complex(2, -3) * 5 == complex(10, -15)
3131

3232
# __neg__

vm/src/obj/objcomplex.rs

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -161,12 +161,22 @@ impl PyComplex {
161161
vm.ctx.new_bool(result)
162162
}
163163

164+
#[pymethod(name = "__float__")]
165+
fn float(&self, vm: &VirtualMachine) -> PyResult {
166+
return Err(vm.new_type_error(String::from("Can't convert complex to float")));
167+
}
168+
169+
#[pymethod(name = "__int__")]
170+
fn int(&self, vm: &VirtualMachine) -> PyResult {
171+
return Err(vm.new_type_error(String::from("Can't convert complex to int")));
172+
}
173+
164174
#[pymethod(name = "__mul__")]
165-
fn mul(self, other: PyObjectRef, vm: &VirtualMachine) -> PyObjectRef {
175+
fn mul(&self, other: PyObjectRef, vm: &VirtualMachine) -> PyResult {
166176
match to_complex(other, vm) {
167177
Ok(Some(other)) => Ok(vm.ctx.new_complex(Complex64::new(
168178
self.value.re * other.re - self.value.im * other.im,
169-
self.value.re * other.im + self.value.re * other.im,
179+
self.value.re * other.im + self.value.im * other.re,
170180
))),
171181
Ok(None) => Ok(vm.ctx.not_implemented()),
172182
Err(err) => Err(err),

0 commit comments

Comments
 (0)