下面是 Python 3.x language reference 中的一段话,大意是理解的,不过写不出一个这样的示例,求大神给个与这段话一致的示例:
When an instance method object is derived from a class method object, the “class instance” stored in self will actually be the class itself, so that calling either x.f(1) or C.f(1) is equivalent to calling f(C,1) where f is the underlying function.
In fact, you will understand this part by doing your own experiments.
Let’s start from the original text and divide it into two paragraphs to discuss. The first paragraph says:
The first paragraph of the original text says that when a
instance method object
被調用時,__func__
的第一個參數先代入class instance
is called, then it gives an example:We use the following example to illustrate, here we have a class
Demo
,他底下有一個 functionfoo
和 functionbar
.Demo
Category:Actually:
Python reference for
foo
,會產生一個 一般的 function,這個 function 會被Demo.foo
.When we write
demo.foo
的時候,Python 會即時創造一個 bound method object:demo.foo
,這個 method object 是個綁定的 method,綁定甚麼呢? 當然就是綁定demo
這個 instance,所以demo.foo.__self__
會參考到demo
, 同時 Python 也會把Demo.foo
記在demo.foo.__func__
in.So treat this
demo.foo
被呼叫的時候(demo.foo(1,2,3)
),他其實會去呼叫demo.foo.__func__
,並且以demo.foo.__self__
(其實也就是demo
self) as the first parameter.If we use the class we wrote to show it, his example becomes:
Look at the code:
Test results:
Then watch the second paragraph:
The main idea of the second paragraph is that when the instance method object comes from the class method object, the
self
class instance that exists in will be the class itself. Then another example is given:We also use examples to illustrate:
Python for bar, will generate
Demo.bar
,他是一個來自於 class method object 的 bound method object,原本Demo.bar
就跟Demo.foo
一樣是個一般的 Python function,但是透過修飾器(@classmethod
修飾器),他成為了一個 bound method object,若要觀察原本的 general function,只能在Demo.bar.__func__
中看到,同時他綁定了Demo
類,所以Demo.bar.__self__
會參考到Demo
class.So when
Demo.bar
被呼叫的時候(Demo.bar(1)
),,他其實會去呼叫Demo.bar.__func__
,並且以Demo.bar.__self__
(其實也就是Demo
itself) is treated as the first parameter.If we use the class we wrote to show it, his example becomes:
Test code:
Test results:
Conclusion:
In Python3, there are two types of funcitons in class, one is a general function object, and the other is a bound method object
Instance method is a method object composed of a general function bound to an instance, and class mehtod is a method object composed of a general function bound to a class
bound method is called, it actually calls the original function (recorded in
__func__
中),但會以綁定的對象作為第一個參數(記在__self__
).References:
Difference between methods and functions
Different way to create an instance method object in Python