python - 在 Python 中动态覆盖 __functions__

标签 python

假设我想在 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/

相关文章:

python - 使用多个 if-else 子句对 pandas 数据框进行矢量化以分割域

python - 我可以在 Python 中使用错误作为 if..else 语句的条件吗?如果是,怎么办?

python - n 倍 FFT 卷积和圆形重叠

python - 使用 python 立即管道

python - Python 中的循环编程(corecursion)——可能吗?

python - 确定 Python 类是抽象基类还是具体类

c++ - 嵌入python报错Import by filename is not supported

python - numpy 中数组的有界和或差

python - 递归调用返回自身迭代器的对象方法

python - 我可以为此使用 python ast 模块吗?