作为彼此方法插件系统,您可以检查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