在Python中实现与接口类似的东西有什么好方法? [英] What's a good way to implement something similar to an interface in Python?

查看:158
本文介绍了在Python中实现与接口类似的东西有什么好方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Python中实现类似于Delphi / C#接口或抽象类的好方法是什么?一个强制所有子类实现一组特定方法的类?

What's a good way to implement something similar to a Delphi/C# interface or abstract class in Python? A class that will force all its subclasses to implement a particular set of methods?

推荐答案

最简单的方法是使用从2.7版本开始包含在Python中的抽象基类实现。

The simplest way to do this is to use the abstract base class implementation that has been included in Python since version 2.7.

这允许您使用 abc将基类标记为抽象。 ABCMeta 元类。然后,您可以将方法和属性标记为抽象。当您使用 ABCMeta 元类(或其任何子类)实例化一个类时,如果实例中未定义任何抽象属性或方法,则会抛出异常。

This lets you mark a base class as abstract by using the abc.ABCMeta metaclass. You may then mark methods and properties as abstract. When you instantiate a class with the ABCMeta metaclass (or any of its subclasses) an exception will be thrown if any abstract properties or methods remain undefined in the instance.

例如

>>> from abc import ABCMeta, abstractmethod
>>> class Foo(object):
    __metaclass__ = ABCMeta
    @abstractmethod
    def bar(self): pass


>>> class BadFoo(Foo):
    pass

>>> BadFoo()

Traceback (most recent call last):
  File "<pyshell#9>", line 1, in <module>
    BadFoo()
TypeError: Can't instantiate abstract class BadFoo with abstract methods bar
>>> class GoodFoo(Foo):
    def bar(self):
        return 42


>>> GoodFoo()
<__main__.GoodFoo object at 0x027354B0>
>>> 

只有在实例化类时才进行检查,因为只有一个子类是完全合法的实现了一些抽象方法,因此它本身就是一个抽象类。

The check is done only when the class is instantiated because it is perfectly legitimate to have a subclass that only implements some of the abstract methods and is therefore itself an abstract class.

这篇关于在Python中实现与接口类似的东西有什么好方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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