First of all: there is a big difference between the concepts of providing and implementing an interface.
基本上,“implement一个接口”,即provide这一接口。 毕竟,这些课程是实例的蓝图,详细说明其执行情况。
现在,一个接口描述了根据具体情况提供的执行情况,但<代码>_init__。 方法不是例子之一! 它是各年级直接提供的接口的一部分(代之以“灰色”术语中的一种分类方法)。 如果您界定了<代码>_init__。 您的接口方法,您宣布,您的事例(<>provide)为_init__
,s well(作为实例方法)。
So interfaces describe what kind of instances you get, not how you get them.
Now, interfaces can be used for more than just describing what functionality an instance provides. You can also use interfaces for any kind object in Python, including modules and classes. You ll have to use the directlyProvides
method to assign an interface to these, as you won t be calling these to create an instance. You can also use the @provider()
class decorator, or the classProvides
or moduleProvides
functions from within a class or module declaration to get the same results.
在此情况下,你想要的是工厂的定义;工厂是工厂,一旦被叫作,就会产生一种情况,因此工厂的界面必须提供<代码>->->->-方法,以表明这些方法是可以使用的。 您树立的榜样是:
from zope import interface
class ITest(interface.Interface):
required_attribute = interface.Attribute(
"""A required attribute for classes implementing this interface.""")
def required_method():
"""A required method for classes implementing this interface."""
class ITestFactory(interface.Interface):
"""Creates objects providing the ITest interface"""
def __call__(a, b):
"""Takes two parameters"""
@interface.implementer(ITest)
@interface.provider(ITestFactory)
class Test(object):
def __init__(self, a, b):
self.required_attribute = a*b
def required_method():
return self.required_attribute
The zope.component
package provides you with a convenience class and interface for factories, adding a getInterfaces
method and a title and description to make discovery and introspection a little easier. You can then just subclass the IFactory
interface to document your __init__
parameters a little better:
from zope import component
class ITestFactory(component.interfaces.IFactory):
"""Creates objects providing the ITest interface"""
def __call__(a, b):
"""Takes two parameters"""
testFactory = component.Factory(Test, ITest Factory , ITestFactory.__doc__)
interface.directlyProvides(testFactory, ITestFactory)
现在,你可以将工厂登记为<代码>zope.component效用,例如,允许其他代码找到所有国际试验公司。
I used zope.interface.directlyProvides
http://www.ohchr.org。 通常只有<代码>tactory接口。