Skip to main content
 首页 » 编程设计

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

2025年05月04日14mate10pro

我没有理解 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举一些例子。