澄清Python教程文档中的段落

我不清楚
python教程文档中的这一段是什么.

(在这里:https://docs.python.org/3/tutorial/classes.html#method-objects)

When an instance attribute is referenced that isn’t a data attribute, its class is searched. If the name denotes a valid class attribute that is a function object, a method object is created by packing (pointers to) the instance object and the function object just found together in an abstract object: this is the method object. When the method object is called with an argument list, a new argument list is constructed from the instance object and the argument list, and the function object is called with this new argument list.

根据我目前的理解,我认为它的含义是每当你引用一个类实例的属性时,就像这个小片段的第8行一样:

class MyClass():
    attribute = "I am an attribute"

    def func(self):
        return "I am a function"

instance = MyClass()
print(instance.func())

当python看到

instance.func()

它真正做的不是寻找一个方法func“拥有”实例,它正在寻找MyClass拥有的函数func,然后调用MyClass拥有的函数,并将实例作为self参数.

所以基本上它是一样的:

MyClass.func(instance)

我觉得我错过了一些微妙的东西.我不明白这意味着什么

… a method object is created by packing (pointers to) the instance object and the function object just found together in an abstract object: this is the method object.

什么是抽象对象?

“打包”指针是什么意思?

“打包”多个指针是什么意思?

为什么甚至有一个方法对象,例如如果python只是要查看MyClass的函数对象?

为什么python不让方法被“实例”拥有?为什么甚至要经历调用MyClass的func而不是实例的func的整个过程?

为什么语言的设计者决定这样做呢?

最佳答案 “抽象对象”意味着不一定要创建真正的Python对象,它只是一种描述幕后发生的事情的方式,就好像有一些对象被创建一样.

“包装”意味着它只是将这些东西收集到这个抽象对象中.

所以当你写作

instance.func()

它在内部创建表示与实例结合的功能的东西.调用此方法时,将按照您的描述调用方法函数,并将实例作为第一个参数传递(通常命名为self).

为什么这样?这样你就可以传递这些东西了:

foo = instance.func
foo()

foo的值包含表示与实例组合的函数的抽象对象.

方法由类拥有,以便类的所有实例自动获得相同的方法.这是OO编程的本质和类之间继承的基础.

点赞