问题
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)
The problem with the constraints here is that in post, I get this error: _holder instance has no attribute 'self'
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
As far as I can tell, PyContract
doesn't like that I call __old__.self
. How do I get around this?
回答1:
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)
source
来源:https://stackoverflow.com/questions/13021011/referencing-self-in-old-in-pycontract-constraints