python中什么是接口_在Python中实现与接口类似的东西有什么好方法?

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?

解决方案

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

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.

e.g.

>>> 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 "", line 1, in

BadFoo()

TypeError: Can't instantiate abstract class BadFoo with abstract methods bar

>>> class GoodFoo(Foo):

def bar(self):

return 42

>>> GoodFoo()

>>>

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值