【发布时间】:2011-01-08 14:42:57
【问题描述】:
public interface IInterface
{
void show();
}
public class MyClass : IInterface
{
#region IInterface Members
public void show()
{
Console.WriteLine("Hello World!");
}
#endregion
}
如何实现此 C# 代码的 Python 等效项?
class IInterface(object):
def __init__(self):
pass
def show(self):
raise Exception("NotImplementedException")
class MyClass(IInterface):
def __init__(self):
IInterface.__init__(self)
def show(self):
print 'Hello World!'
这是个好主意吗?请在你的回答中举例说明。
【问题讨论】:
-
在您的案例中使用接口的目的是什么?
-
坦白说根本没有目的!我只是想学习在python中需要接口的时候怎么办?
-
raise NotImplementedError应该是show的主体——当 Python 定义了一个完全特定的内置函数时,提出一个完全通用的Exception是没有意义的!-) -
不应该 init 在 IInterface 中调用 show() (或引发异常本身),这样您就无法实例化抽象接口?
-
我可以看到它的一些用途......假设您有一个要确保具有特定签名的对象。使用鸭子类型,您不能保证对象将具有您期望的签名。有时对动态类型的属性强制执行一些类型可能很有用。