gpt4 book ai didi

python - 从类中的一个方法继承的两个方法在实例上是不同的,不是吗?

转载 作者:太空宇宙 更新时间:2023-11-03 14:01:26 24 4
gpt4 key购买 nike

谁能解释一下为什么会这样?

class Foo:
def bar(self):
pass

a = Foo()
b = Foo()

a.bar == b.bar # False
a.bar is b.bar # False

我以为他们都继承了类方法,而且是一个方法。

最佳答案

当您通过在类上定义的实例访问函数时,每次都会创建一个绑定(bind)方法 对象。来自docs :

What exactly happens when a method is called? You may have noticed that x.f() was called without an argument above, even though the function definition for f() specified an argument. What happened to the argument? Surely Python raises an exception when a function that requires an argument is called without any — even if the argument isn’t actually used…

Actually, you may have guessed the answer: the special thing about methods is that the instance object is passed as the first argument of the function. In our example, the call x.f() is exactly equivalent to MyClass.f(x). In general, calling a method with a list of n arguments is equivalent to calling the corresponding function with an argument list that is created by inserting the method’s instance object before the first argument.

If you still don’t understand how methods work, a look at the implementation can perhaps clarify matters. 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.

请注意,每次访问方法时都会发生这种情况:

>>> class Foo:
... def bar(self): pass
...
>>> f = Foo()
>>> f.bar is f.bar
False

这是如何运作的?嗯,实际上,functions are descriptor objects ,请注意 __get__ 的存在:

>>> def func(): pass
...
>>> func.__get__
<method-wrapper '__get__' of function object at 0x101e38ae8>

换句话说,您可以认为 Python 函数是这样实现的:

class Function(object):
. . .
def __get__(self, obj, objtype=None):
"Simulate func_descr_get() in Objects/funcobject.c"
if obj is None:
return self
return types.MethodType(self, obj)

当然,它们不是用 Python 实现的(至少在 CPython 中是这样!)。

另请注意,直接在类上访问该函数当然不会这样做(至少在您已在问题中标记的 Python 3 上):

>>> Foo.bar is Foo.bar
True

关于python - 从类中的一个方法继承的两个方法在实例上是不同的,不是吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48736670/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com