我有两个继承自同一父 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 继承自元组和 P ,而 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()可以正常工作!
我什至可以呼叫 d.foo()。
推荐答案在 object .__ new __ 中测试了抽象方法。 code>方法;当您从具有自己的 __ 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.
换句话说,将抽象方法与 any 混合内置的不可变类型将导致此问题。
In other words, mixing abstract methods with any of the built-in immutable types will cause this problem.
唯一有效的解决方案是在 __ new __ 中进行 own 测试仅当在子类的两个基中混合时将抽象类放在之前 元组。
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使用abstractmethod的不同行为
发布评论