【问题标题】:Referencing `self` in `__old__` in PyContract constraints在 PyContract 约束中的 __old__ 中引用 `self`
【发布时间】:2012-10-22 22:43:41
【问题描述】:

我正在使用PyContract(不是PyContracts)为类方法编写一些约束。作为后置条件,我想确保实例的内存地址没有改变,即id(self) 在调用函数之前和之后应该是相同的。我怎样才能用 PyContract 做到这一点? 我有以下(最少的)代码:

class Individual:
    def append(self, chrom):
        """
            post:
                __old__.self is self
                len(__old__.self.chromosomes)+1 == len(self.chromosomes)
                self.chromosomes[-1] == chrom
        """
        self.chromosomes.append(chrom)

这里的约束问题是,在帖子中,我收到了这个错误:_holder instance has no attribute 'self'

这里有趣的是class Individual 有一个__init__,其约束如下所示:

pre:
    isinstance(chromosomes, list)
post[chromosomes]:
    __old__.chromosomes is chromosomes
    __old__.chromosomes == chromosomes
post:
    hasattr(self, 'chromosomes')
    self.chromosomes == chromosomes

据我所知,PyContract 不喜欢我打电话给__old__.self。我该如何解决这个问题?

【问题讨论】:

    标签: python self design-by-contract contract


    【解决方案1】:

    这似乎解决了它:

    class Individual:
        def append(self, chrom):
            """
                post[self]:
                    __old__.self is self
                    len(__old__.self.chromosomes)+1 == len(self.chromosomes)
                    self.chromosomes[-1] == chrom
            """
            self.chromosomes.append(chrom)
    

    source

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-02
      • 2018-08-02
      • 1970-01-01
      • 1970-01-01
      • 2018-08-06
      • 2016-08-14
      相关资源
      最近更新 更多