写一个existsong python模块的扩展

时间:2016-03-30 00:52:19

标签: python pycairo

我想写一个扩展到python的lib cairo。计划如下:

cairo有一个名为" Context"这是用户在其上绘制几何对象的画布。

例如,让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"的文件,但我不知道如何实现它。我想知道在这种情况下编写现有模块扩展的标准/优雅方式是什么?感谢任何有用的建议。

1 个答案:

答案 0 :(得分:1)

Subclassing是你的朋友。只需继承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

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