我使用zope.interface模块来声明带有一些方法和属性的接口。而且,我不能以某种方式声明属性名,而且声明它们的类型吗?
from zope.interface import Interface, Attribute, implementer, verify
class IVehicle(Interface):
"""Any moving thing"""
speed = Attribute("""Movement speed""") #CANNOT I DECLARE ITS TYPE HERE?
def move():
"""Make a single step"""
pass发布于 2014-05-30 16:06:49
您可以通过引入invariant来限制属性的类型。
from zope.interface import Interface, Attribute, implementer, verify, invariant
def speed_invariant(ob):
if not isinstance(ob.speed, int):
raise TypeError("speed must be an int")
class IVehicle(Interface):
"""Any moving thing"""
speed = Attribute("""Movement speed""")
invariant(speed_invariant)
def move():
"""Make a single step"""
pass您的IVehicle类有一个validateInvariants方法,您可以调用它来验证实现它的类中没有任何不变量被破坏。
IVehicle.validateInvariants(vechile_instance)不过,我不知道如何直接指定属性的类型。
https://stackoverflow.com/questions/23958295
复制相似问题