Skip to content

Commit d1e0feb

Browse files
committed
Add pure Python Cython implementation
1 parent d179ef2 commit d1e0feb

File tree

4 files changed

+73
-5
lines changed

4 files changed

+73
-5
lines changed

source-code/cython/Classes/Makefile

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,12 @@
11
VERSION = cpython-311-x86_64-linux-gnu
2-
PRIMES_LIB = primes_cython.$(VERSION).so
2+
POINTS_LIB = points.$(VERSION).so
3+
POINTS_PURE_LIB = points_pure.$(VERSION).so
34

4-
all: $(PRIMES_LIB)
5+
all: $(POINTS_LIB)
56

6-
$(PRIMES_LIB): points.pyx
7+
$(POINTS_LIB): points.pyx points_pure.py
78
python setup.py build_ext --inplace
89

910
clean:
1011
python setup.py clean
11-
$(RM) primes_cython.c $(PRIMES_LIB)
12+
$(RM) points.c points_pure.c $(POINTS_LIB) $(POINTS_PURE_LIB)
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
#!/usr/bin/env python
2+
3+
import pyximport
4+
pyximport.install(pyimport=True, language_level='3str')
5+
6+
from points_pure import Point, ColoredPoint
7+
8+
p = Point(1.0, -2.0)
9+
print(p)
10+
print(f'point = {p.x}, {p.y}')
11+
print(p.distance())
12+
13+
p1 = ColoredPoint(1.0, -2.0, 'blue')
14+
print(p1.color)
Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
import cython
2+
from math import sqrt
3+
4+
@cython.cclass
5+
class Point:
6+
7+
x: cython.float
8+
y: cython.float
9+
10+
def __init__(self, x: cython.float, y: cython.float) -> None:
11+
self.x = x
12+
self.y = y
13+
14+
def distance(self) -> cython.float:
15+
return sqrt(self.x**2 + self.y**2)
16+
17+
@property
18+
def x(self) -> cython.float:
19+
return self.x
20+
21+
@x.setter
22+
def x(self, value: cython.float) -> None:
23+
self.x = float(value)
24+
25+
@property
26+
def y(self) -> cython.float:
27+
return self.y
28+
29+
@y.setter
30+
def y(self, value: cython.float) -> None:
31+
self.y = float(value)
32+
33+
def __str__(self) -> str:
34+
return f"Point({self.x}, {self.y})"
35+
36+
37+
class ColoredPoint(Point):
38+
39+
def __init__(self, x, y, color):
40+
super().__init__(x, y)
41+
self._color = color
42+
43+
@property
44+
def color(self):
45+
return self._color
46+
47+
@color.setter
48+
def color(self, value):
49+
self._color = str(value)
50+
51+
def __str__(self):
52+
return f"ColoredPoint({self.x}, {self.y}, {self.color})"

source-code/cython/Classes/setup.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,5 +4,6 @@
44
from Cython.Build import cythonize
55

66
setup(
7-
ext_modules=cythonize('points.pyx', language_level='3str')
7+
ext_modules=cythonize(['points.pyx', 'points_pure.py'],
8+
language_level='3str')
89
)

0 commit comments

Comments
 (0)