Class invariants in Python

后端 未结 2 2024
长情又很酷
长情又很酷 2021-02-15 16:35

Class invariants definitely can be useful in coding, as they can give instant feedback when clear programming error has been detected and also they improve code readability as b

2条回答
  •  粉色の甜心
    2021-02-15 17:03

    Please have a look at icontract library. We developed it to bring design-by-contract into Python with informative error messages. Here as an example of a class invariant:

    >>> @icontract.inv(lambda self: self.x > 0)
    ... class SomeClass:
    ...     def __init__(self) -> None:
    ...         self.x = 100
    ...
    ...     def some_method(self) -> None:
    ...         self.x = -1
    ...
    ...     def __repr__(self) -> str:
    ...         return "some instance"
    ...
    >>> some_instance = SomeClass()
    >>> some_instance.some_method()
    Traceback (most recent call last):
     ...
    icontract.ViolationError: self.x > 0:
    self was some instance
    self.x was -1
    

提交回复
热议问题