Python与抽象方法的不同行为 [英] Python different behaviour with abstractmethod

查看:31
本文介绍了Python与抽象方法的不同行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个类继承自同一个父P:

I have two classes inheriting from the same parent P:

from abc import ABCMeta, abstractmethod

class P(object):

    __metaclass__ = ABCMeta

    @abstractmethod  
    def foo(self):
        pass

class C(P):
    pass

class D(tuple, P):
    pass

唯一的区别是D继承自tupleP,而C继承自P 仅.

The only difference is that D inherited from tuple and P while C inherits from P only.

现在这是行为:c = C() 出现错误,正如预期的那样:

Now this is the behavior: c = C() got error, as expected:

TypeError: Can't instantiate abstract class C with abstract methods foo

但是 d = D() 可以正常工作!

but d = D() works without error!

我什至可以调用 d.foo().我该如何解释这种行为?

I can even call d.foo(). How can I explain this behaviour?

推荐答案

抽象方法在 object.__new__ 方法中进行测试;当您从具有自己的 __new__ 方法的 tuple 继承时,不会调用 object.__new__ 并且不会对抽象方法进行测试.

Abstract methods are tested for in the object.__new__ method; when you inherit from tuple, which has its own __new__ method, object.__new__ is not called and the test for abstract methods is not made.

换句话说,将抽象方法与任何的内置不可变类型混合会导致这个问题.

In other words, mixing abstract methods with any of the built-in immutable types will cause this problem.

唯一有效的解决方案是在 __new__ 中进行自己的 测试,然后仅当您将抽象类放在 之前元组在子类中混合两个基时.

The only solution that works is to do your own test in __new__ and then only if you put your abstract class before tuple when mixing in the two bases in a subclass.

class P(object):
    __metaclass__ = ABCMeta

    def __new__(cls, *args, **kwargs):
        super_new = super(P, cls).__new__
        if super_new.__self__ is not object:
            # immutable mix-in used, test for abstract methods
            if getattr(cls, '__abstractmethods__'):
                raise TypeError(
                    "Can't instantiate abstract class %s "
                    "with abstract methods %s" % (
                        cls.__name__,
                        ', '.join(sorted(cls.__abstractmethods__))))

        return super_new(cls, *args, **kwargs)

    @abstractmethod  
    def foo(self):
        pass

class D(P, tuple):
    pass

这篇关于Python与抽象方法的不同行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆