-
Notifications
You must be signed in to change notification settings - Fork 31
Expand file tree
/
Copy pathclass_example_test.go
More file actions
64 lines (53 loc) · 1.29 KB
/
class_example_test.go
File metadata and controls
64 lines (53 loc) · 1.29 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
package py_test
import (
"fmt"
"gopython.xyz/py/v3"
)
// myClass is the type that represents the custom class in Go.
type myClass struct {
py.ClassBaseObject
}
// Call is the method called when the type is called in Python.
//
// This is one of many optional functions that can be implemented on the custom
// class type to respond to actions in Python.
func (m *myClass) Call(args *py.Tuple, kwds *py.Dict) (py.Object, error) {
var s string
if err := py.ParseTuple(args, "s", &s); err != nil {
return nil, err
}
fmt.Printf("hello %s", s)
return py.None, nil
}
// myClassType is a py.Class value that is the Type of myClass.
var myClassType = py.Class{
Name: "MyClass",
Flags: py.ClassBaseType,
Doc: "An example Class",
Object: (*myClass)(nil),
}
func ExampleClass() {
lock := py.InitAndLock()
defer lock.Finalize()
// we have to Create the Class before we can use it
if err := myClassType.Create(); err != nil {
fmt.Printf("ERROR: %s", err)
return
}
// Python: "m = MyClass()"
m, err := myClassType.CallGo(nil, nil)
if err != nil {
fmt.Printf("ERROR: %s", err)
return
}
defer m.Decref()
// Python: "m("world")"
o, err := m.Base().CallGo(py.A{"world"}, nil)
if err != nil {
fmt.Printf("ERROR: %s", err)
return
}
defer o.Decref()
// Output:
// hello world
}