forked from EveryTimeIWill18/Cython_Repo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCython_Tutorial_Four.pyx
117 lines (90 loc) · 2.55 KB
/
Cython_Tutorial_Four.pyx
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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
import numpy
cpdef long f1(long x, long y):
return x % y
cdef long f2(long x, long y):
return x % y
def pyf1(long[:] x, long[:] y):
cdef long result = 0
for i in range(x.shape[0]):
result += f1(x[i], y[i])
return result
def pyf2(long[:] x, long[:] y):
cdef long result = 0
for i in range(x.shape[0]):
result += f2(x[i], y[i])
return result
x = numpy.random.randint(1, 100, 2**20)
y = numpy.random.randint(1, 100, 2**20)
print(x[:5])
# cython inheritence and polymorphism
# class inheritence using cython classes
cdef class A:
"""Cython parent class A"""
cdef int x
def __init__(self, x):
self.x = x
cdef class B(A):
"""Cython subclass B"""
cdef int y
def __init__(self, x, y):
super().__init__(x)
self.v = y
class C(B):
"""Python subclass of Cython class B"""
def __init__(self, x, y, z):
super().__init__(x, y)
self.z = z
from libc.stdlib cimport malloc, realloc, free
# remember, __cinit__ is only called once.
# super() will not call __cinit__
# __cinit__ useful for allocating memory
cdef class AA:
cdef char* x # x is a pointer to a char
def __cinit__(self, int size):
self.x = <char *>malloc(size * sizeof(char))
cdef class BB(AA):
def __init__(self, size):
# does not call A.__cinit__
super().__init__(size)
cdef class AAA:
def f(self):
return 'A'
cdef class BBB(AAA):
def f(self):
return 'B'
# test out polymorphism
bbb = BBB()
print(dir(bbb))
# cython oop
cdef class Bird:
"""Cython class, Bird"""
cdef public:
double weight # ounces
def __init__(self, weight):
self.weight = weight
def weight_ratio(self, carry_weight):
return carry_weight/self.weight
cdef class Swallow(Bird):
"""Cython subclass, Swallow"""
cdef public:
bint migratory # True/False
def __init__(self, weight, migratory):
super().__init__(weight)
self.migratory = migratory
## example
bird1 = Bird(5)
bird2 = Bird(7)
bird3 = Bird(100)
swallow = Swallow(5, True)
print(swallow.weight_ratio(16))
cdef class Parent:
cdef str dancing_style(self):
return "Waltz"
cdef class Child(Parent):
cdef str dancing_style(self):
return "Break dancing"
cdef Parent obj # declare a var called obj, type: Parent
cdef Parent obj2 # create another instance of Parent
obj = Child() # create an instance of Child, subclass
print(obj.dancing_style())
print(obj2.dancing_style())