Skip to content

Commit d05bbcc

Browse files
raffncw
authored andcommitted
complex: added __str__ and __repr__ plus missing properties
Added __str__ and __repr__ plus missing properties (real, imag, conjugate). Also added tests.
1 parent 4f66e54 commit d05bbcc

File tree

2 files changed

+61
-0
lines changed

2 files changed

+61
-0
lines changed

py/complex.go

+27
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
package py
88

99
import (
10+
"fmt"
1011
"math"
1112
"math/cmplx"
1213
)
@@ -60,6 +61,14 @@ func convertToComplex(other Object) (Complex, bool) {
6061
return 0, false
6162
}
6263

64+
func (a Complex) M__str__() (Object, error) {
65+
return String(fmt.Sprintf("(%g%+gj)", real(complex128(a)), imag(complex128(a)))), nil
66+
}
67+
68+
func (a Complex) M__repr__() (Object, error) {
69+
return a.M__str__()
70+
}
71+
6372
func (a Complex) M__neg__() (Object, error) {
6473
return -a, nil
6574
}
@@ -286,6 +295,24 @@ func (a Complex) M__ge__(other Object) (Object, error) {
286295
return a.M__lt__(other)
287296
}
288297

298+
// Properties
299+
func init() {
300+
ComplexType.Dict["real"] = &Property{
301+
Fget: func(self Object) (Object, error) {
302+
return Float(real(self.(Complex))), nil
303+
},
304+
}
305+
ComplexType.Dict["imag"] = &Property{
306+
Fget: func(self Object) (Object, error) {
307+
return Float(imag(self.(Complex))), nil
308+
},
309+
}
310+
ComplexType.Dict["conjugate"] = MustNewMethod("conjugate", func(self Object) (Object, error) {
311+
cnj := cmplx.Conj(complex128(self.(Complex)))
312+
return Complex(cnj), nil
313+
}, 0, "conjugate() -> Returns the complex conjugate.")
314+
}
315+
289316
// Check interface is satisfied
290317
var _ floatArithmetic = Complex(complex(0, 0))
291318
var _ richComparison = Complex(0)

py/tests/complex.py

+34
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
# Copyright 2018 The go-python Authors. All rights reserved.
2+
# Use of this source code is governed by a BSD-style
3+
# license that can be found in the LICENSE file.
4+
5+
from libtest import assertRaises
6+
7+
doc="str"
8+
assert str(3+4j) == "(3+4j)"
9+
10+
doc="repr"
11+
assert repr(3+4j) == "(3+4j)"
12+
13+
doc="real"
14+
assert (3+4j).real == 3.0
15+
16+
doc="imag"
17+
assert (3+4j).imag == 4.0
18+
19+
doc="conjugate"
20+
assert (3+4j).conjugate() == 3-4j
21+
22+
doc="add"
23+
assert (3+4j) + 2 == 5+4j
24+
assert (3+4j) + 2j == 3+6j
25+
26+
doc="sub"
27+
assert (3+4j) - 1 == 2+4j
28+
assert (3+4j) - 1j == 3+3j
29+
30+
doc="mul"
31+
assert (3+4j) * 2 == 6+8j
32+
assert (3+4j) * 2j == -8+6j
33+
34+
doc="finished"

0 commit comments

Comments
 (0)