2016-03-30 85 views
1

我想写一个扩展到Python的lib开罗。计划如下:写一个扩展到existong python模块

cairo有一个名为“Context”的类,它是用户在其上绘制几何对象的画布。

例如让CR是背景信息的一个实例,则

cr.move_to(a,b) 
cr.line_to(c,d) 

将笔移动到(A,B),然后画一条线到(C,d)。

我想添加另一个方法到这个库,例如它被命名为“My_line_to”:这个函数将绘制(a,b)和(c,d)之间的曲线,而不是一条直线(我仍然调用它LINE_TO(),因为它在双曲几何测地线)

用法

cr.my_move_to(a,b) 
cr.my_line_to(c,d) 

我想我最好还是让这个扩展到一个名为“MyDrawer.py”另一个文件,但我不知道如何实现这一点。我想知道在这种情况下编写扩展模块的标准/优雅方式是什么?感谢您提供有用的建议。

+0

我发现了一个重复的问题:http://stackoverflow.com/questions/2705964/how-do-i-extend-a-python-module-python-twitter –

回答

1

子类是你的朋友在这里。只需划分Context类并定义一个附加方法。

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 

然后,当您想要使用这个新类时,只需导入它并使用它。