python : how to make subclasses 'closed' under methods inherited from its superclass

标签 python class inheritance

我知道我应该想出一个更好的标题,但无论如何......

假设我在 python 中创建了一个继承自 int 的类:

class Foo(int):

    def is_even(self):
        return self%2 == 0

然后做这样的事情

a = Foo(3)
b = Foo(5)
print(type(a+b)) #=> <class 'int'>

我知道这种行为一点也不奇怪,因为这里调用的 __add___ 被定义为返回 int 实例。但我想创建一个类,以便 a+b 返回 Foo(8)。换句话说,我希望结果 a+b 具有 is_even 方法。

有什么方法可以方便地实现这一点?还是我必须覆盖 __add__ 和所有内容?

背景信息:我正在尝试为 an esoteric programming language called Grass 编写解释器.在那次尝试中,我想要一个行为类似于“callable-int”(实际上是 numpy.uint8)的类,其 __call__ 会像

def __call__(self, other):
    if self == other:
        return lambda x: lambda y: x
    else:
        return lambda x: lambda y: y

.

最佳答案

您可以使用元类(__metaclass__ 类变量)或 __getattribute__ 特殊方法来技巧。但是the documentation状态:

Bypassing the getattribute() machinery in this fashion provides significant scope for speed optimisations within the interpreter, at the cost of some flexibility in the handling of special methods (the special method must be set on the class object itself in order to be consistently invoked by the interpreter)

这意味着如果你想确保永远不会直接处理父类,你需要拦截一切。对于 int,它被描述为 emulating numeric types (即:实现所有这些方法)。


就是说,我相信您可以通过创建一个采用两个参数并仅对它们调用 super 的 lambda 或泛型方法,轻松地在您的类中实现所有这些方法。然后将该方法分配给您需要实现的所有特定方法。因此,您只需实现一次即可重用

关于 python : how to make subclasses 'closed' under methods inherited from its superclass,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20579397/

相关文章:

java - Java编译器无法解析覆盖的JButton的符号

oop - 如何访问由继承类的init方法创建的变量?

python - 使用 irc.bot.SingleServerIRCBot 保留线程(与 twitch 一起使用)

c++ - 制作动态对象数组问题?

jquery - 克隆 div 中输入 block 的 AJAX 更新

python - 如何在Python中通过继承正确启动子类?

c++ - 使用继承的成员运算符而不是免费的成员运算符

python - 验证 Pandas 数据框中的行在列中的值之间是否相等

python - 我如何洗牌有约束的列表(1 和 2、3 和 4、5 和 6 不相邻)?

python - 使用python从mysql查询列表中提取ip地址