为什么 CPython 会创建同一个方法的多个实例?
Why does CPython create multiple instances of the same method?
>>> (1).__str__!=(2).__str__
True
为什么将它们设为单独的对象而不是指单个对象,是否有任何技术原因?好像效率会更高
那是因为您没有得到 __str__
函数,而是它的方法包装器。
>>> x = (1).__str__
>>> type(x)
<class 'method-wrapper'>
>>> x()
'1'
>>> x.__self__
1
>>> x = (2).__str__
>>> x()
'2'
>>> x.__self__
2
方法包装器是一个保留对 self
引用的对象。所以每个实例都必须不同。
有关详细信息,请查看 this question。
>>> (1).__str__!=(2).__str__
True
为什么将它们设为单独的对象而不是指单个对象,是否有任何技术原因?好像效率会更高
那是因为您没有得到 __str__
函数,而是它的方法包装器。
>>> x = (1).__str__
>>> type(x)
<class 'method-wrapper'>
>>> x()
'1'
>>> x.__self__
1
>>> x = (2).__str__
>>> x()
'2'
>>> x.__self__
2
方法包装器是一个保留对 self
引用的对象。所以每个实例都必须不同。
有关详细信息,请查看 this question。