为了将SOLID原则应用于有机增长且需要重构的 Python 项目,我试图了解接口隔离原则如何应用于Python语言,当接口不存在时语言功能?
问问题
2737 次
2 回答
17
接口是您可以在源代码中直接输入提示或在文档中非正式地输入提示的东西。Python 3 支持函数注释、3.5+ 实际类型提示,即使所有这些都不存在,您仍然可以在文档中简单地输入提示。类型提示只是表示特定参数应具有特定特征。
更具体地说:
interface Foo {
string public function bar();
}
function baz(Foo obj) { .. }
所有这一切都是声明传入的任何参数baz
都应是一个对象,该对象具有bar
不带参数并返回字符串的方法。即使 Python 没有在语言级别实现任何东西来强制执行此操作,您仍然可以通过多种方式声明这些东西。
Python 确实支持两个重要的东西:抽象类和多重继承。
而不是interface Foo
,在 Python 中你这样做:
import abc
class Foo(abc.ABC):
@abc.abstractmethod
def bar() -> str:
pass
而不是implements Foo
,你做:
class MyClass(Foo):
def bar() -> str:
return 'string'
而不是function baz(Foo obj)
,你做:
def baz(obj: Foo):
obj.bar()
由于多重继承功能,您可以根据需要尽可能精细地隔离接口/抽象类。
Python基于鸭子类型原则,因此不是通过接口声明和继承来强制执行所有这些,它通常更宽松地定义为“参数必须是可迭代的”等,调用者只需确保参数是可迭代的。抽象类和函数注释,再加上正确的开发工具,可以帮助开发人员在不同的执行级别上遵守此类合同。
于 2015-10-09T12:13:10.033 回答
0
保持接口小而简洁会减少耦合。耦合是指两个软件之间连接的紧密程度。接口定义的越多,实现类也需要做的越多。这使得该类的可重用性降低。
我们来看一个简单的例子:
from abc import abstractmethod
class Machine:
def print(self, document):
raise NotImplementedError()
def fax(self, document):
raise NotImplementedError()
def scan(self, document):
raise NotImplementedError()
# ok if you need a multifunction device
class MultiFunctionPrinter(Machine):
def print(self, document):
pass
def fax(self, document):
pass
def scan(self, document):
pass
class OldFashionedPrinter(Machine):
def print(self, document):
# ok - print stuff
pass
def fax(self, document):
pass # do-nothing
def scan(self, document):
"""Not supported!"""
raise NotImplementedError('Printer cannot scan!')
class Printer:
@abstractmethod
def print(self, document): pass
class Scanner:
@abstractmethod
def scan(self, document): pass
# same for Fax, etc.
class MyPrinter(Printer):
def print(self, document):
print(document)
class Photocopier(Printer, Scanner):
def print(self, document):
print(document)
def scan(self, document):
pass # something meaningful
class MultiFunctionDevice(Printer, Scanner): # , Fax, etc
@abstractmethod
def print(self, document):
pass
@abstractmethod
def scan(self, document):
pass
class MultiFunctionMachine(MultiFunctionDevice):
def __init__(self, printer, scanner):
self.printer = printer
self.scanner = scanner
def print(self, document):
self.printer.print(document)
def scan(self, document):
self.scanner.scan(document)
printer = OldFashionedPrinter()
printer.fax(123) # nothing happens
printer.scan(123) # oops!
于 2021-03-07T22:12:09.347 回答