Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does the __self__ attribute of method become a class rather a instance?

The documentation of instance methods confused me, it classifies methods into two types:the one is retrieved by an instance of a class, the other is created by retrieving a method from a class or instance.

According to the description,

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.

the __self__ attribute of the more complex methods is a class. Can someone show me a example to illustrate the situation?

like image 526
wow yoo Avatar asked Sep 06 '25 03:09

wow yoo


1 Answers

The statement may have sounded ambiguous when you read it like that. I'll try to break it down.

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.

So if we have a obj = TestClass() then

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

and

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

This statement is specifically about instance methods created from class's class methods.

I hope it is clearer. I have created a snippet here for you to play around with.

like image 141
zEro Avatar answered Sep 07 '25 17:09

zEro