在PyContract约束中的“旧”中引用“self”

2024-05-13 04:09:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用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)

这里约束的问题是,在post中,我得到了以下错误:_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。我该怎么办?你知道吗


Tags: 方法selflenis条件postoldindividual
1条回答
网友
1楼 · 发布于 2024-05-13 04:09:57

这似乎解决了问题:

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

相关问题 更多 >