我不清楚 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
“属于”instance
的方法,它正在寻找一个func
拥有的函数MyClass
,然后使用 instance
作为 self
参数调用 MyClass
拥有的函数。
所以基本上它是一样的:
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
的函数对象,为什么还要为 instance
设置一个方法对象?
为什么 python 不直接让方法被它们的实例“拥有”?为什么还要经历调用 MyClass
的 func
而不是 instance
的 func
的整个过程?
为什么语言的设计者决定采用这种方式?
最佳答案
“抽象对象”意味着不一定要创建一个真正的 Python 对象,它只是一种描述幕后发生的事情的方式,就好像正在创建某个对象一样。
“打包”的意思就是把这些东西集合在一起,变成这个抽象的对象。
所以当你写的时候
instance.func()
它在内部创建了一些代表函数与实例相结合的东西。调用此函数时,将按照您的描述调用方法函数,并将实例作为第一个参数传递(通常命名为 self
)。
为什么要这样做?这样你就可以传递这些东西:
foo = instance.func
foo()
foo
的值包含表示与实例组合的函数的抽象对象。
方法由类拥有,因此类的所有实例自动获得相同的方法。这是面向对象编程的本质,也是类间继承的基础。
关于python - 对 Python 教程文档中一段的说明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50848237/