面向对象、接口编程的重要性 python 为什么引入接口interface
面向对象编程的实践
有个产品,其有10个子产品,现在要统计每日消费数据
其中8个子产品的消费入账金额算法相同,2个不同;
拓展性差的糟糕的代码
def ConsumptionSum(product):
product_id = product.get(product)
if product == 'p1':
return p1CS()
if product == 'p2':
return p2CS()
PEP 245 -- Python Interface Syntax | Python.org https://www.python.org/dev/peps/pep-0245/
PEP 245 -- Python Interface Syntax
| PEP: | 245 |
|---|---|
| Title: | Python Interface Syntax |
| Author: | Michel Pelletier <michel at users.sourceforge.net> |
| Discussions-To: | http://www.zope.org/Wikis/Interfaces |
| Status: | Rejected |
| Type: | Standards Track |
| Created: | 11-Jan-2001 |
| Python-Version: | 2.2 |
| Post-History: | 21-Mar-2001 |
Formal Interface Syntax
Python syntax is defined in a modified BNF grammar notation described in the Python Reference Manual [8]. This section describes the proposed interface syntax using this grammar:
interfacedef: "interface" interfacename [extends] ":" suite
extends: "(" [expression_list] ")"
interfacename: identifier
This PEP also proposes an extension to Python's 'class' statement:
classdef: "class" classname [inheritance] [implements] ":" suite
implements: "implements" implist
implist: expression-list classname,
inheritance,
suite,
expression-list: see the Python Reference Manual
The Problem
Interfaces are important because they solve a number of problems that arise while developing software:
- There are many implied interfaces in Python, commonly referred to as "protocols". Currently determining those protocols is based on implementation introspection, but often that also fails. For example, defining __getitem__ implies both a sequence and a mapping (the former with sequential, integer keys). There is no way for the developer to be explicit about which protocols the object intends to implement.
- Python is limited, from the developer's point of view, by the split between types and classes. When types are expected, the consumer uses code like 'type(foo) == type("")' to determine if 'foo' is a string. When instances of classes are expected, the consumer uses 'isinstance(foo, MyString)' to determine if 'foo' is an instance of the 'MyString' class. There is no unified model for determining if an object can be used in a certain, valid way.
- Python's dynamic typing is very flexible and powerful, but it does not have the advantage of static typed languages that provide type checking. Static typed languages provide you with much more type safety, but are often overly verbose because objects can only be generalized by common subclassing and used specifically with casting (for example, in Java).
There are also a number of documentation problems that interfaces try to solve.
- Developers waste a lot of time looking at the source code of your system to figure out how objects work.
- Developers who are new to your system may misunderstand how your objects work, causing, and possibly propagating, usage errors.
- Because a lack of interfaces means usage is inferred from the source, developers may end up using methods and attributes that are meant for "internal use only".
- Code inspection can be hard, and very discouraging to novice programmers trying to properly understand code written by gurus.
- A lot of time is wasted when many people try very hard to understand obscurity (like undocumented software). Effort spend up front documenting interfaces will save much of this time in the end.
Interfaces try to solve these problems by providing a way for you to specify a contractual obligation for your object, documentation on how to use an object, and a built-in mechanism for discovering the contract and the documentation.
Python has very useful introspection features. It is well known that this makes exploring concepts in the interactive interpreter easier, because Python gives you the ability to look at all kinds of information about the objects: the type, doc strings, instance dictionaries, base classes, unbound methods and more.
Many of these features are oriented toward introspecting, using and changing the implementation of software, and one of them ("doc strings") is oriented toward providing documentation. This proposal describes an extension to this natural introspection framework that describes an object's interface.
Overview of the Interface Syntax
For the most part, the syntax of interfaces is very much like the syntax of classes, but future needs, or needs brought up in discussion, may define new possibilities for interface syntax.
A formal BNF description of the syntax is givena later in the PEP, for the purposes of illustration, here is an example of two different interfaces created with the proposed syntax:
interface CountFishInterface:
"Fish counting interface" def oneFish():
"Increments the fish count by one" def twoFish():
"Increments the fish count by two" def getFishCount():
"Returns the fish count" interface ColorFishInterface:
"Fish coloring interface" def redFish():
"Sets the current fish color to red" def blueFish():
"Sets the current fish color to blue" def getFishColor():
"This returns the current fish color"
This code, when evaluated, will create two interfaces called CountFishInterface and ColorFishInterface. These interfaces are defined by the interface statement.
The prose documentation for the interfaces and their methods come from doc strings. The method signature information comes from the signatures of the def statements. Notice how there is no body for the def statements. The interface does not implement a service to anything; it merely describes one. Documentation strings on interfaces and interface methods are mandatory, a 'pass' statement cannot be provided. The interface equivalent of a pass statement is an empty doc string.
You can also create interfaces that "extend" other interfaces. Here, you can see a new type of Interface that extends the CountFishInterface and ColorFishInterface:
interface FishMarketInterface(CountFishInterface, ColorFishInterface):
"This is the documentation for the FishMarketInterface" def getFishMonger():
"Returns the fish monger you can interact with" def hireNewFishMonger(name):
"Hire a new fish monger" def buySomeFish(quantity=1):
"Buy some fish at the market"
The FishMarketInteface extends upon the CountFishInterface and ColorfishInterface.
Interface Assertion
The next step is to put classes and interfaces together by creating a concrete Python class that asserts that it implements an interface. Here is an example FishMarket component that might do this:
class FishError(Error):
pass class FishMarket implements FishMarketInterface:
number = 0
color = None
monger_name = 'Crusty Barnacles' def __init__(self, number, color):
self.number = number
self.color = color def oneFish(self):
self.number += 1 def twoFish(self):
self.number += 2 def redFish(self):
self.color = 'red' def blueFish(self):
self.color = 'blue' def getFishCount(self):
return self.number def getFishColor(self):
return self.color def getFishMonger(self):
return self.monger_name def hireNewFishMonger(self, name):
self.monger_name = name def buySomeFish(self, quantity=1):
if quantity > self.count:
raise FishError("There's not enough fish")
self.count -= quantity
return quantity
面向对象、接口编程的重要性 python 为什么引入接口interface的更多相关文章
- 【PHP面向对象(OOP)编程入门教程】20.PHP5接口技术(interface)
PHP与大多数面向对象编程语言一样,不支持多重继承.也就是说每个类只能继承一个父类.为了解决这个问题,PHP引入了接口,接口的思想是指定了一个实现了该接口的类必须实现的一系列方法.接口是一种特殊的抽象 ...
- 吴裕雄--天生自然JAVA面向对象高级编程学习笔记:抽象类与接口的应用
abstract class A{ // 定义抽象类A public abstract void print() ; // 定义抽象方法print() }; class B extends A { / ...
- PHP面向对象(OOP)编程入门教程
面向对象编程(OOP)是我们编程的一项基本技能,PHP5对OOP提供了良好的支持.如何使用OOP的思想来进行PHP的高级编程,对于提高 PHP编程能力和规划好Web开发构架都是非常有意义的.下面我们就 ...
- Mybatis接口编程原理分析(二)
在上一篇博客中 Mybatis接口编程原理分析(一)中我们介绍了MapperProxyFactory和MapperProxy,接下来我们要介绍的是MapperMethod MapperMethod:它 ...
- 谈面向对象的编程(Python)
(注:本文部分内容摘自互联网,由于作者水平有限,不足之处,还望留言指正.) 今天中秋节,也没什么特别的,寻常日子依旧. 谈谈面向对象吧,什么叫面向对象? 那么问题来了,你有对象吗? 嗯,,,那我可 ...
- python学习笔记--面向对象的编程和类
一.面向对象的编程 面向对象程序设计--Object Oriented Programming,简称oop,是一种程序设计思想.二.面向对象的特性类:class类,对比现实世界来说就是一个种类,一个模 ...
- Python 中的面向接口编程
前言 "面向接口编程"写 Java 的朋友耳朵已经可以听出干茧了吧,当然这个思想在 Java 中非常重要,甚至几乎所有的编程语言都需要,毕竟程序具有良好的扩展性.维护性谁都不能拒绝 ...
- 【GoLang】golang 面向对象编程 & 面向接口编程
005.面向对象&接口编程 1 面向函数编程 1.1 将数据作为参数传递到函数入参 1.2 对象与函数是分离的 2 面向对象编程 2.1 使用者看起来函数作为对象的属性而非参数 2.2 函数属 ...
- IT第十九天 - 继承、接口、多态、面向对象的编程思想
IT第十九天 上午 继承 1.一般情况下,子类在继承父类时,会调用父类中的无参构造方法,即默认的构造方法:如果在父类中只写了有参的构造方法,这时如果在子类中继承时,就会出现报错,原因是子类继承父类时无 ...
随机推荐
- 【Oracle】查找每期数据都存在的产品
现在存在以下数据 如上图:A01与A02同时存在201710.201711.201712中 我们现在要将其查找出来 如果上图的表结构如下: 那么查询的SQL如下: SELECT DISTINCT CO ...
- c与c++中的强制类型转换区别
强制类型转换的一般形式为: (类型名)(表达式) 如:(int)a.这是C语言使用的形式,C++把它保留了下来,以利于兼容. C++还增加了以下形式: 类型名(表达式) 如:int(a).这种形式类似 ...
- STM32F103RB, KEIL编译出错:cannot open preprocessing output output file ".\神舟i号\main.d" no such file or
STM32F103RB, KEIL编译出错:cannot open preprocessing output output file ".\神舟i号\main.d" no su ...
- (一)Shiro笔记——简介、 架构分析
1. Shiro是什么 Apache Shiro是一个强大灵活的开源安全框架,可以完全处理身份验证,授权,企业会话管理和加密. Apache Shiro的首要目标是易于使用和理解. 安全有时可能非常复 ...
- Python内置函数之all()
all()函数返回值不是True就是False. 它只能传入一个参数,而且参数必须是可迭代对象,换句话说,参数不是元组就是列表(通常情况下). all()中的可迭代对象所有元素值为True或者不包含元 ...
- mysql5.7.22 zip 版安装
2.将zip文件解压到本地,本文解压到如下目录:D:\softwares\mysql-5.7.14-winx64 3.新建一个配置文件(my.ini)用于配置字符集.端口等信息,用以覆盖原始的配置文件 ...
- Flex读取txt文件里的内容报错
Flex读取txt文件里的内容 1.详细错误例如以下 2.错误原因 读取文件不存在 var file:File = new File(File.applicationDirectory.nativeP ...
- IOS设计模式浅析之单例模式(Singleton)
说在前面 进入正式的设计模式交流之前,扯点闲话.我们在项目开发的过程中,经常会不经意的使用一些常见的设计模式,如单例模式.工厂方法模式.观察者模式等,以前做.NET开发的时候,认真拜读了一下程杰老师的 ...
- 关于LNMP服务器 Thinkphp5验证码不显示问题
关于LNMP服务器 Thinkphp5验证码不显示问题 浏览:246 发布日期:2017/09/20 分类:ThinkPHP5专区 关键字: thinkphp验证码不显示 nginx下验证码不显示 ...
- 深度历险:Redis 内存模型详解
https://mp.weixin.qq.com/s/Gp6Ur7omGY6ZqDWygU2meQ Redis 是目前最火爆的内存数据库之一,通过在内存中读写数据,大大提高了读写速度,可以说 Redi ...