忘记自我限定词:如何发现这个错误?
我理解为什么 Python 在引用实例属性时需要显式的 self 限定符。
但我经常忘记它,因为我在 C++ 中不需要它。
我以这种方式引入的错误有时非常难以捕获;例如,假设我写的
if x is not None:
f()
是
if self.x is not None:
f()
假设属性x
通常是None
,所以很少调用f()
。假设f()
只会产生微妙的副作用(例如,数值的更改或清除缓存等)。除非我进行了大量的单元测试,否则这个错误可能会在很长一段时间内被忽视。
我想知道是否有人知道可以帮助我捕获或避免此类错误的编码技术或 IDE 功能。
I understand why Python requires explicit self
qualifier when referring to instance attributes.
But I often forget it, since I didn't need it in C++.
The bug I introduce this way is sometimes extremely hard to catch; e.g., suppose I write
if x is not None:
f()
instead of
if self.x is not None:
f()
Suppose attribute x
is usually None
, so f()
is rarely called. And suppose f()
only creates a subtle side effect (e.g., a change in a numeric value, or clearing the cache, etc.). Unless I have insane amount of unit tests, this mistake is likely to remain unnoticed for a long time.
I am wondering if anyone knows coding techniques or IDE features that could help me catch or avoid this type of bug.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
不要将实例属性命名为与全局/局部变量相同的名称。
如果没有同名的全局/本地,当您尝试访问 self.foo 时,您将收到
global "foo" is not Defined
错误,但是忘记自我。
。作为推论:为变量提供描述性名称。不要将所有内容命名为
x
- 这不仅会大大降低您拥有与属性同名的变量的可能性,而且还使您的代码更易于阅读。Don't name your instance attributes the same things as your globals/locals.
If there isn't a global/local of the same name, you'll get a
global "foo" is not defined
error when you try to accessself.foo
but forget theself.
.As a corollary: give your variables descriptive names. Don't name everything
x
- not only does this make it far less likely you'll have variables with the same name as attributes, it also makes your code easier to read.