使用type()进行方法调用

时间:2011-08-01 14:55:48

标签: python

为什么PEP-343在这种情况下使用type()?

    mgr = (EXPR)
    exit = type(mgr).__exit__  # Not calling it yet
    value = type(mgr).__enter__(mgr)

我们不能使用exit = mgr.__exit__value = mgr.__enter__()吗?对我来说似乎更简单,但我认为我错过了一些东西。

2 个答案:

答案 0 :(得分:5)

当然,PEP 可以使用实例本身的属性而不是类型的属性,但这与在Python中使用特殊方法形成对比。例如

a + b

被翻译为

type(a).__add__(a, b)

a.__add__(b)

如以下示例所示:

>>> class MyInt(int):
...     pass
... 
>>> a = MyInt(3)
>>> b = MyInt(4)
>>> a + b
7
>>> a.__add__ = lambda self, other: 42
>>> a + b
7

因此,为了与Python的其余部分保持一致,还应首先在类型的字典中查找特殊方法__enter__()__exit__()

答案 1 :(得分:2)

上面的构造获取mgr对象的类型(类)的 unbound 方法,否则mgr dict被激活并获得绑定方法。< / p>

相关问题