【问题标题】:Cannot I declare an attribute with type in zope.interface?我不能在 zope.interface 中声明具有类型的属性吗?
【发布时间】:2014-05-30 15:36:33
【问题描述】:

我使用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

【问题讨论】:

    标签: python zope.interface


    【解决方案1】:

    你可以通过引入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)
    

    不过,我不知道直接指定属性类型的方法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-09-06
      • 1970-01-01
      • 1970-01-01
      • 2022-01-17
      • 2015-05-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多