python - 为什么在 Python 中没有从对象的方法中引用对象成员的简写?

标签 python class oop

我没有理解 Python 教程中的以下句子:

there are no shorthands for referencing the object's members from it's methods.The method function is declared with an explicit 1st argument representing the object, which is provided implicitly by the call.

这是否意味着,在一个类的每个方法中,它的对象与数据成员一起被隐藏了?这可以用示例代码解释吗?

最佳答案

这只是指在对象的方法中,对象本身始终是第一个参数(即 def method(self, arg1, arg2) 中的“self”),并且您需要在方法中明确说明您想要 self.var 而不是仅仅说 var

有关做出该决定的原因的更多背景信息,请参阅 https://docs.python.org/2/faq/design.html#why-must-self-be-used-explicitly-in-method-definitions-and-calls来自文档或 http://neopythonic.blogspot.com.au/2008/10/why-explicit-self-has-to-stay.html举一些例子。

关于python - 为什么在 Python 中没有从对象的方法中引用对象成员的简写?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33265846/

相关文章:

python - 在 Python 中将 np.arrays 附加到空白数组

python - 不构建模型时,占位符和变量之间有区别吗?

python - 在 Windows 上从 python 运行 Stardew Valley

oop - 私有(private)与 protected - 可见性良好实践关注

python - OOP 和 Python 的新手 -- 关于存储大量对象的问题

python - Pandas - 带公式的列

c++ - 打印对象数组的每个元素时出现问题

python - Python 方法名称末尾的括号是什么?

java - 当键为 `String[]` 时,是否有一种有效的方法来检查存储在 HashMap 中的键是否等于测试键?

swift - 初始化类对象 swift 3