public interface IInterface
{
void show();
}
public class MyClass : IInterface
{
#region IInterface Members
public void show()
{
Console.WriteLine("Hello World!");
}
#endregion
}
我如何实现Python等效的这个c#代码?
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 3.8以结构子类型(静态鸭子类型)(PEP 544)的形式为主题提供了什么。
参见简短说明https://docs.python.org/3/library/typing.html#typing.Protocol
下面这个简单的例子是这样的:
from typing import Protocol
class MyShowProto(Protocol):
def show(self):
...
class MyClass:
def show(self):
print('Hello World!')
class MyOtherClass:
pass
def foo(o: MyShowProto):
return o.show()
foo(MyClass()) # ok
foo(MyOtherClass()) # fails
foo(MyOtherClass())将失败的静态类型检查:
$ mypy proto-experiment.py
proto-experiment.py:21: error: Argument 1 to "foo" has incompatible type "MyOtherClass"; expected "MyShowProto"
Found 1 error in 1 file (checked 1 source file)
此外,你可以显式地指定基类,例如:
class MyOtherClass(MyShowProto):
但请注意,这使得基类的方法实际上在子类上可用,因此静态检查器将不会报告MyOtherClass上缺少方法定义。
因此,在这种情况下,为了获得有用的类型检查,我们希望显式实现的所有方法都应该使用@abstractmethod来装饰:
from typing import Protocol
from abc import abstractmethod
class MyShowProto(Protocol):
@abstractmethod
def show(self): raise NotImplementedError
class MyOtherClass(MyShowProto):
pass
MyOtherClass() # error in type checker
接口支持Python 2.7和Python 3.4+。
要安装接口,你必须
pip install python-interface
示例代码:
from interface import implements, Interface
class MyInterface(Interface):
def method1(self, x):
pass
def method2(self, x, y):
pass
class MyClass(implements(MyInterface)):
def method1(self, x):
return x * 2
def method2(self, x, y):
return x + y