假设我想在 Python 类中覆盖像 __int__
这样的函数,这样我就可以做这样的事情。
class A(object):
def __init__(self):
self.__int__ = lambda: 1
a = A()
print int(a)
我希望它会在这里输出“1”而不是产生这个错误信息
TypeError: int() argument must be a string or a number, not 'A'
当 __int__
改为内置到类中的方法时,它会按预期工作。为什么? (这个问题也存在于任何双下划线函数中)
最佳答案
这似乎是 __
魔术方法中的又一点魔术。与其他方法不同,它们在隐式调用时不会查找类实例。
有据可查的是,它们无法通过 __getattribute__
魔术方法得到解决(如果它们这样做了,那将是一个很好的悖论,因为 __getattribute__
必须调用自己来解析自己的名字)。但不检查实例让我感到惊讶。
这里在标题“特殊方法查找”下进行了一些讨论: http://segfaulthunter.github.io/articles/biggestsurprise/
For instances of new-style classes, all special method lookup that is done implicitely is done in the class struct. Thus changing an instance's
__str__
attribute does not effect the result of str(). Still, explicitely getting the attribute from the instance gives you the method in the instance.
我很想知道是否还有其他人可以提供更详细的解释。
关于python - 在 Python 中动态覆盖 __functions__,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19750394/