为现有 python 模块编写扩展
Write an extension to an existing python module
我想为 python 的库 cairo
写一个扩展。方案如下:
cairo
有一个名为"Context"的class就是用户在上面绘制几何对象的canvas
例如让cr
成为Context的一个实例,那么
cr.move_to(a,b)
cr.line_to(c,d)
将笔移动到(a,b),然后画一条线到(c,d)。
我想在这个lib中添加另一个方法,例如它被命名为"My_line_to":这个函数将在(a,b)和(c,d)之间绘制一条曲线,而不是一条直线。(我仍然称它为 line_to() 因为它是双曲几何中的测地线)
用法是
cr.my_move_to(a,b)
cr.my_line_to(c,d)
我想我最好把这个扩展放到另一个名为 "MyDrawer.py" 的文件中,但我不知道如何实现它。我想知道在这种情况下,standard/elegant 编写现有模块扩展的方法是什么?
Subclassing 是你的朋友。只需 subclass Context
class 并定义一个附加方法。
from cairo import Context # or whatever is the path name
class ExtendedContext(Context): # subclass from ExtendedContext - inherits all methods and variables from Context
def my_line_to(self, x, y):
# define code here
def my_move_to(self, x, y):
# define code here
然后,当你想使用这个新的class时,只需导入并使用它。
我想为 python 的库 cairo
写一个扩展。方案如下:
cairo
有一个名为"Context"的class就是用户在上面绘制几何对象的canvas
例如让cr
成为Context的一个实例,那么
cr.move_to(a,b)
cr.line_to(c,d)
将笔移动到(a,b),然后画一条线到(c,d)。
我想在这个lib中添加另一个方法,例如它被命名为"My_line_to":这个函数将在(a,b)和(c,d)之间绘制一条曲线,而不是一条直线。(我仍然称它为 line_to() 因为它是双曲几何中的测地线)
用法是
cr.my_move_to(a,b)
cr.my_line_to(c,d)
我想我最好把这个扩展放到另一个名为 "MyDrawer.py" 的文件中,但我不知道如何实现它。我想知道在这种情况下,standard/elegant 编写现有模块扩展的方法是什么?
Subclassing 是你的朋友。只需 subclass Context
class 并定义一个附加方法。
from cairo import Context # or whatever is the path name
class ExtendedContext(Context): # subclass from ExtendedContext - inherits all methods and variables from Context
def my_line_to(self, x, y):
# define code here
def my_move_to(self, x, y):
# define code here
然后,当你想使用这个新的class时,只需导入并使用它。