Python使用abstractmethod的不同行为

编程入门 行业动态 更新时间:2024-10-18 03:34:28
本文介绍了Python使用abstractmethod的不同行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有两个继承自同一父 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的不同行为

本文发布于:2023-11-15 23:30:51,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1598931.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:Python   abstractmethod

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!