【发布时间】:2012-05-11 05:31:16
【问题描述】:
Python 3 中的方法包装器类型是什么?如果我这样定义一个类:
class Foo(object):
def __init__(self, val):
self.val = val
def __eq__(self, other):
return self.val == other.val
然后做:
Foo(42).__eq__
我明白了:
<bound method Foo.__eq__ of <__main__.Foo object at 0x10121d0>>
但如果我这样做(在 Python 3 中):
Foo(42).__ne__
我明白了:
<method-wrapper '__ne__' of Foo object at 0x1073e50>
什么是“方法包装器”类型?
编辑:抱歉更准确地说:class method-wrapper 是 __ne__ 的类型,好像我一样:
>>> type(Foo(42).__ne__)
<class 'method-wrapper'>
而__eq__ 的类型是:
>>> type(Foo(42).__eq__)
<class 'method'>
此外,method-wrapper 似乎是类上任何未定义的魔法方法的类型(因此,__le__、__repr__、__str__ 等如果未明确定义也将具有这种类型)。
我感兴趣的是 Python 如何使用 method-wrapper 类。类上方法的所有“默认实现”都只是这种类型的实例吗?
【问题讨论】:
标签: types python-3.x