作爲彼此方法插件系統,您可以檢查Extend Me project。
例如,讓我們定義簡單的類及其延伸
# Define base class for extensions (mount point)
class MyCoolClass(Extensible):
my_attr_1 = 25
def my_method1(self, arg1):
print('Hello, %s' % arg1)
# Define extension, which implements some aditional logic
# or modifies existing logic of base class (MyCoolClass)
# Also any extension class maby be placed in any module You like,
# It just needs to be imported at start of app
class MyCoolClassExtension1(MyCoolClass):
def my_method1(self, arg1):
super(MyCoolClassExtension1, self).my_method1(arg1.upper())
def my_method2(self, arg1):
print("Good by, %s" % arg1)
,並嘗試使用它:
>>> my_cool_obj = MyCoolClass()
>>> print(my_cool_obj.my_attr_1)
25
>>> my_cool_obj.my_method1('World')
Hello, WORLD
>>> my_cool_obj.my_method2('World')
Good by, World
並表現出什麼是隱藏在幕後:
>>> my_cool_obj.__class__.__bases__
[MyCoolClassExtension1, MyCoolClass]
extend_me庫操作類的創建ocess通過元類,從而例如在上面的MyCoolClass
創建新實例時,我們得到了新的類的實例,它是兩者具有MyCoolClassExtension
和MyCoolClass
功能兩者的子類,由於Python的multiple inheritance
在過去的階級創造更好的控制有在此lib中定義的幾元類:
該庫在OpenERP Proxy Project使用,似乎是工作不夠好!
有關使用方法的實際例子,看看在OpenERP Proxy 'field_datetime' extension:
from ..orm.record import Record
import datetime
class RecordDateTime(Record):
""" Provides auto conversion of datetime fields from
string got from server to comparable datetime objects
"""
def _get_field(self, ftype, name):
res = super(RecordDateTime, self)._get_field(ftype, name)
if res and ftype == 'date':
return datetime.datetime.strptime(res, '%Y-%m-%d').date()
elif res and ftype == 'datetime':
return datetime.datetime.strptime(res, '%Y-%m-%d %H:%M:%S')
return res
Record
這裏是extesible對象。 RecordDateTime
是擴展名。
要啓用擴展,包含擴展類只是導入模塊,和(如果上文)之後創建的所有Record
對象將具有在基類擴展類,因此具有其所有功能。
這個庫的主要優點是,運行可擴展對象的代碼不需要知道擴展和擴展就可以改變可擴展對象中的所有內容。
+1第二段。如此真實。 :-) – 2012-04-03 06:29:11
非常感謝!我寫了一個基於你的帖子的小教程:http://lkubuntu.wordpress.com/2012/10/02/writing-a-python-plugin-api/ – MiJyn 2012-10-03 18:06:10
'imp`模塊被棄用,贊成'importlib `從python 3.4 – b0fh 2017-08-30 08:56:57