Skip to main content
 首页 » 编程设计

python之Python 解释器是否将实例绑定(bind)到方法或 self 参数

2024年10月01日6Free-Thinker

我正在阅读一本关于 Python 面向对象编程的书。有一句话让我很困惑:

The interpreter automatically binds the instance upon which the method is invoked to the self parameter.

在这句话中什么是绑定(bind)到实例的。方法,还是 self 参数?

请您参考如下方法:

这实际上不是一个糟糕的问题,我不确定为什么它这么快就被否决了......

尽管 Python 支持面向对象,但我发现它更接近函数式编程语言,原因之一是函数是“在”对象上调用的,而不是“由”对象调用的。

例如:len(obj) 在“真正的”面向对象的编程语言中,您希望能够执行类似 obj.length() 的操作

关于 self 参数,您正在调用 obj.method(other_args) 但真正发生的是将此调用转换为:method(obj, other_args) 您可以看到,当声明该方法时,您正在使用作为第一个参数传入的 self 变量来执行此操作:

class ... 
 
    def method(self, other_args): 
    ... 

所以这基本上都是关于 obj.method(other_args) 到 method(obj, other_args) 的“翻译”