Python @property 异常行为:调试器引发self.updated误更新
VS Code调试器触发@property属性导致状态异常问题
我实现了一个管理单词集合的Universe类,通过@property装饰器定义了uncertainty属性,用于计算集合的不确定性。在使用+=运算符添加元素时,会将实例的self.updated标记为False,但调试过程中发现self.updated始终保持True;当我移除@property装饰器,将uncertainty改为普通方法后,程序行为符合预期。
最终定位到问题根源:Visual Studio Code调试器会自动调用类的@property属性,这会触发uncertainty属性的计算逻辑,从而把self.updated重新设为True,干扰了原本的状态判断。
完整代码示例
import math from typing import Self import re FREQUENCIES: dict[str, float] = {} FREQUENCIES['trial'] = 0.023 FREQUENCIES['raise'] = 0.124 def entropy(probability: float) -> float: if probability == 0.0: return 0.0 return -probability*math.log(probability)/math.log(2.0) class Word(str): def __new__(cls, value: str = 'aaaaa') -> Self: value = value.strip().lower() if not re.match(r'[a-z]{5}', value): raise ValueError(f'"{value}" does not follow the pattern [a-z]{5}!') return super().__new__(cls, value) def __init__(self, value: str = 'aaaaa') -> None: self.frequency = FREQUENCIES[value] class Universe(set[Word]): def __init__(self) -> None: super().__init__(set()) self.frequency = 0.0 self.statistics: dict[int, dict[str, float]] = {} self.updated = True def __iadd__(self, word: Word) -> Self: if word in self: return self self.updated = False self.add(word) return self @property def uncertainty(self) -> float: if not self.updated: self.frequency = sum(word.frequency for word in self) self.statistics = {i: {chr(letter): sum(wordle.frequency for wordle in self if wordle[i] == chr(letter)) for letter in range(ord('a'), ord('z')+1)} for i in range(len(Word()))} self.updated = True return sum(sum(entropy(letterFrequency/self.frequency) for letterFrequency in self.statistics[position].values()) for position in self.statistics)
使用示例
universe = Universe() universe += Word('trial') universe += Word('raise') print(f'My universe has {len(universe)} words and an uncertainty of {universe.uncertainty} bits.')
内容的提问来源于stack exchange,提问作者Nuno
相关产品推荐
相关产品推荐

