方法的self属性如何变成类而不是实例?

2024-04-24 08:02:49 发布

您现在位置:Python中文网/ 问答频道 /正文

实例方法的文档把我弄糊涂了,它把方法分为两类类型:一另一个是通过从类或实例中检索方法创建的。你知道吗

根据描述

When an instance method object is created by retrieving a class method object from a class or instance, its __self__ attribute is the class itself, and its __func__ attribute is the function object underlying the class method.

更复杂方法的__self__属性是一个类。 有人能给我举个例子来说明情况吗?你知道吗


Tags: the实例方法instance文档selfan类型
1条回答
网友
1楼 · 发布于 2024-04-24 08:02:49

当你这样读的时候,这句话听起来可能有点模棱两可。我试着把它分解一下。你知道吗

When an instance method object is created by retrieving a class method object from a class or instance...

class TestClass(object):
    @classmethod
    def test_method(cls):
        return 1

its __self__ attribute is the class itself, and its __func__ attribute is the function object underlying the class method.

如果我们有一个obj = TestClass(),那么

obj.test_method.__self__ == TestClass.test_method.__self__

以及

obj.test_method.__func__ == TestClass.test_method.__func__

此语句专门针对从类的类方法创建的实例方法。你知道吗

我希望它更清楚。我已经创建了一个片段here供您使用。你知道吗

相关问题 更多 >