为什么我们不能把“自我”分解成一个方法?

2024-05-15 07:54:47 发布

您现在位置:Python中文网/ 问答频道 /正文

>>> class Potato(object):
...     def method(self, spam):
...         print self, spam
... 
>>> spud = Potato()

作品:

^{pr2}$

不起作用:

>>> Potato.method(**{'self': spud, 'spam': 123})
# TypeError

但为什么不呢?我认为“自我”只是一种惯例,而这一论点本身并没有什么特别之处?在


Tags: selfobjectdefspammethod作品classpotato
1条回答
网友
1楼 · 发布于 2024-05-15 07:54:47

Python2的instancemethod包装器对象坚持检查第一个位置参数,并且该检查不支持关键字参数,句号

>>> Potato.method(self=spud, spam=123)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unbound method method() must be called with Potato instance as first argument (got nothing instead)

请注意,我没有在这里使用参数解包!在

可以很好地使用位置参数:

^{pr2}$

也可以访问原始函数对象:

>>> Potato.method.__func__(**{'self': spud, 'spam': 123})
<__main__.Potato object at 0x1002b57d0> 123

绕过这个限制。在

Python3不再对未绑定的方法使用方法包装器;而是直接返回底层函数。在

相关问题 更多 >