2016-03-30 89 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 

然後,當您想要使用這個新類時,只需導入它並使用它。