Use of type() for method calls
Why does PEP-343 use type() in this situation here?
mgr = (EXPR)
exit = type(mgr).__exit__ # Not calling it yet
value = type(mgr).__enter__(mgr)
Couldn't we just as well use exit = mgr.__exit__
and value = mgr.__enter__()
? Seems simpler to me, but I开发者_开发知识库 assume I'm missing something.
Of course the PEP could use attributes of the instance itself instead of attributes of the type, but this would be in contrast to the use of special methods in Python. For example
a + b
is translated to
type(a).__add__(a, b)
and not to
a.__add__(b)
as shown by the following example:
>>> class MyInt(int):
... pass
...
>>> a = MyInt(3)
>>> b = MyInt(4)
>>> a + b
7
>>> a.__add__ = lambda self, other: 42
>>> a + b
7
So, to be consistent with the rest of Python, the special methods __enter__()
and __exit__()
should also be looked up in the type's dictionary first.
The above construct gets the unbound method of the type (class) of the mgr
object, otherwise the mgr
dict is acessed and you get the bound method.
精彩评论