You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

representation invariant(表示不变量)通俗解释及IntSet相关疑问

解答

表示不变量的通俗说明

你可以把表示不变量理解为类的所有合法实例从创建到销毁的全生命周期中,必须始终满足的硬性规则,是这个类对外承诺的特性底线。

比如你现在用的IntSet是模拟整数集合的类,集合的核心特性就是元素不重复,所以这个类给自己定的死规则就是:每个实例存储元素的属性里绝对不能出现重复值,这个规则就是它的表示不变量。

  • 实例初始化的时候(调用__init__),空列表天然没有重复元素,相当于创建实例的时候就遵守了规则
  • 后续你调用insert/remove等所有公开方法操作实例时,方法内部的逻辑都会自动保证操作结束后,存储元素的属性依然符合「无重复」的要求,不会破坏规则

有这个不变量的好处是你用这个类的时候完全不用关心内部实现,也不用自己额外检查元素是否重复,只要你按照方法的注释要求传参(比如insert传整数),这个类永远会符合集合的特性。


关于vals属性的疑问

这里的vals不是类属性,是每个IntSet实例单独持有的实例属性,就是你在__init__方法里看到的self.vals:

class IntSet(object):
    def __init__(self):
        """Create an empty set of integers"""
        self.vals = []
    def insert(self, e):
        """Assumes e is an integer and inserts e into self"""
        if not e in self.vals:
            self.vals.append(e)
    def member(self, e):
        """Assumes e is an integer
        Returns True if e is in self, and False otherwise"""
        return e in self.vals
    def remove(self, e):
        """Assumes e is an integer and removes e from self
        Raises ValueError if e is not in self"""
        try:
            self.vals.remove(e)
        except:
            raise ValueError(str(e) + ' not found')
    def getMembers(self):
        """Returns a list containing the elements of self.
        Nothing can be assumed about the order of the elements"""
        return self.vals[:]

self指向的是你创建的每一个IntSet实例,每个实例的vals都是独立的列表,各自满足无重复的规则。


内容的提问来源于stack exchange,提问作者Robert John

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 23:45:02