Skip to main content
 首页 » 编程设计

python之方法的 __file__ 属性如何成为类而不是实例

2024年10月17日10zfyouxi

实例方法的文档让我很困惑,它将方法分为两种类型:一种是通过类的实例检索的,另一种是通过从类或实例中检索方法创建的。

根据描述,

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__属性就是一个类。 谁能给我举个例子来说明情况?

请您参考如下方法:

当您这样阅读时,该声明可能听起来模棱两可。我会尝试分解它。

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供您玩耍。