在PyContract约束中的__old__中引用self [英] Referencing `self` in `__old__` in PyContract constraints
问题描述
我正在使用 PyContract (不是 PyContracts ).作为后置条件,我想确保实例的内存地址未更改,即id(self)
在调用函数之前和之后应该相同.如何使用PyContract做到这一点?
我有以下(最小)代码:
I'm working on writing some constraints for a class method using PyContract (not PyContracts). As a postcondition, I'd like to ensure that the memory address of the instance hasn't changed i.e. id(self)
should be the same before and after calling the function. How can I do this with PyContract?
I have the following (minimal) code:
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'
The problem with the constraints here is that in post, I get this error: _holder instance has no attribute 'self'
有趣的是,class Individual
有一个__init__
,其约束如下所示:
The interesting thing here is that class Individual
has an __init__
whose constraints look like this:
pre:
isinstance(chromosomes, list)
post[chromosomes]:
__old__.chromosomes is chromosomes
__old__.chromosomes == chromosomes
post:
hasattr(self, 'chromosomes')
self.chromosomes == chromosomes
据我所知,PyContract
不喜欢我叫__old__.self
.我该如何解决?
As far as I can tell, PyContract
doesn't like that I call __old__.self
. How do I get around this?
推荐答案
这似乎可以解决该问题:
This seems to fix it:
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)
这篇关于在PyContract约束中的__old__中引用self的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!