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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With