Reputation: 3601
I'm using zope.interface
module to declare an interface with some methods and attributes. Also, cannot I somehow declare not only the attribute names, but also their types?
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
Upvotes: 0
Views: 186
Reputation: 94951
You can restrict the type of the attribute by introducing an 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
your IVehicle
class has a validateInvariants
method you can call to validate none of the invariants are being broken in classes that implement it.
IVehicle.validateInvariants(vechile_instance)
I don't know of a way to specify the type of the Attribute directly, though.
Upvotes: 1