Python中构造函数和方法有什么不同?可以将它们混合吗?
我实现了一个可以插拔的框架,像下面这样。
它能正常工作,但我对Plugin2的实现有点困惑。看起来它使用的是一个普通的方法,而不是一个类的构造函数。
这样做可以吗?有什么缺点吗?
这是一个常用的“模式”吗?如果是的话,这个模式叫什么?是“鸭子类型”吗?我应该避免这样使用吗?
更新:我担心的是下面这个方法:
def addPlugin(name, plugin)
现在参数plugin可以是一个类,也可以是一个方法。这对插件开发者来说有点模糊。这在动态编程语言中是常见的情况吗?
class MyFramework(object):
_plugins = {}
_osType = None
@staticmethod
def addPlugin(name, plugin):
MyFramework._plugins[name]= plugin
def __init__(self, osType):
self._osType = osType
for name, plugin in MyFramework._plugins.items():
setattr(self, name, plugin(self, self._osType))
class Plugin1(object):
def __init__(self, owner, osType):
self.owner= owner
self.osType = osType
def hello(self):
print 'this is plugin1'
def Plugin2(owner, osType):
if (osType == "Linux"):
return Plugin2Linux(owner)
else:
return Plugin2Common(owner)
class Plugin2Linux(object):
def __init__(self, owner):
self.owner= owner
def hello(self):
print 'this is plugin2 Linux version'
class Plugin2Common(object):
def __init__(self, owner):
self.owner= owner
def hello(self):
print 'this is plugin2 common version'
MyFramework.addPlugin("plugin1", Plugin1)
MyFramework.addPlugin("plugin2", Plugin2)
framework = MyFramework("Linux")
plugin1 = getattr(framework, "plugin1")
plugin2 = getattr(framework, "plugin2")
plugin1.hello()
plugin2.hello()
2 个回答
0
Plugin2 是一个模块功能,它返回一个对象;而 Plugin1 是一个类,它返回自己这个类的一个实例。
这样做是可以的,不过 Python 推荐的编码标准建议函数名用小写字母(http://www.python.org/dev/peps/pep-0008/),所以应该写成 plugin2。
为了保持一致性,我建议也把 plugin1 写成一个模块功能,这样在你后续的实现中会更统一。
4
这是一种常用的模式,叫做工厂函数。让你的接口可以接受任何可以调用的东西(比如函数或类),只要它能返回一个对象,这样做是个好主意。这样可以让你在将来做事情时更加灵活。