python- abstract - Interface - Polymorphism

Abstract class

What is an abstract class
and, like java, python also has the concept of an abstract class, but also need the aid of module implementation, an abstract class is a special class, it special is that can only be inherited, can not be instantiated. An abstract class is a class abstract pile extracting the same content, which includes the attributes and attribute data functions.
python abstract class implemented
see the following code:

class Wechatpay:
    def __init__(self, name, money):
        self.name = name
        self.money = money

    def pay(self):
        print('%s通过微信支付了%s元' % (self.name, self.money))


class Alipay:
    def __init__(self, name, money):
        self.name = name
        self.money = money

    def pay(self):
        print('%s通过支付宝支付了%s元' % (self.name, self.money))


# 为了归一化设计
def pay(person):  # 直接传入一个对象,对象调用pay方法 ,不管的alipay和Wechatpay
    person.pay()


# 实列化对象
ali = Alipay("Tom", 10000)
wch = Alipay("Jack", 100)

pay(ali)
pay(wch)

Above such calls are no problem, but one day, in order to demand, you need to add applepay function, but defined in applepay
not defined pay method, but is defined to be Chinese pinyin fuqian method is as follows:

class ApplePay:
    def __init__(self, name, money):
        self.name = name
        self.money = money

    def fuqian(self):
        print('%s通过apple pay支付了%s元' % (self.name, self.money))

app = ApplePay("Tom", 1000)
app.fuqian()

By ApplePay above the instantiated objects, fuqian method is invoked without any problems, then to a normalized design, we
use applyPay instantiate an object, the object will be passed to pay function, the following error occurs information, there is no way to pay

pay(app)  # AttributeError: 'ApplePay' object has no attribute 'pay'

That how to deal with this problem?
As long as processing issues, only the extent of regulation of the process, the function definition when it is necessary to set the same function name, as in the above-described method fuqian ApplePay and should be replaced in the Pay WechatPlay Alipay and, what is performed normalized design time, this method can not be found will not appear. Abc module for use in python specification, specific use is as follows:

from abc import ABCMeta,abstractmethod
class Payment(metaclass=ABCMeta):    # 抽象类

    @abstractmethod   # 如果我必须要实现pay方法,那么我需要给pay加一个装饰器
    def pay(self):
        pass   # 创建的这个pay并没有内容,
               # 之所以写一个pay是为了提醒所有子类你一定要实现一个pay方法

    @abstractmethod
    def back(self):
        pass

class Wechatpay(Payment):
    def __init__(self,name,money):
        self.name = name
        self.money = money
    def pay(self):
        print('%s通过微信支付了%s元'%(self.name,self.money))

class Alipay(Payment):
    def __init__(self,name,money):
        self.name = name
        self.money = money
    def pay(self):
        print('%s通过支付宝支付了%s元'%(self.name,self.money))

class ApplePay(Payment):
    def __init__(self, name, money):
        self.name = name
        self.money = money
    def pay(self):
        print('%s通过apple pay支付了%s元' % (self.name, self.money))
    def back(self):
        print('退款')

# 归一化设计
def pay(person):
    person.pay()

ApplePay('alex',20000)

Special attention is being syntactic sugar decorative function, if not created in the subclass Payment implemented in a class, then in the instance of a subclass of time, it will lead to error. As follows:

from abc import ABCMeta,abstractmethod
class Payment(metaclass=ABCMeta):    # 抽象类

    @abstractmethod   # 如果我必须要实现pay方法,那么我需要给pay加一个装饰器
    def pay(self):
        pass   # 创建的这个pay并没有内容,
               # 之所以写一个pay是为了提醒所有子类你一定要实现一个pay方法

    @abstractmethod
    def back(self):
        pass

class Wechatpay(Payment):
    def __init__(self,name,money):
        self.name = name
        self.money = money
    def pay(self):
        print('%s通过微信支付了%s元'%(self.name,self.money))

class Alipay(Payment):
    def __init__(self,name,money):
        self.name = name
        self.money = money
    def pay(self):
        print('%s通过支付宝支付了%s元'%(self.name,self.money))

class ApplePay(Payment):
    def __init__(self, name, money):
        self.name = name
        self.money = money
    # def pay(self):  
    #     print('%s通过apple pay支付了%s元' % (self.name, self.money))
    # def back(self):
    #     print('退款')

# 归一化设计
def pay(person):
    person.pay()

ApplePay('alex',20000)

The above code, the method ApplePay will pay annotated, performing ApplePay ( 'alex', 20000) instantiation, the following errors occurred:

TypeError: Can't instantiate abstract class ApplePay with abstract methods back, pay

to sum up:

Abstract class: Payment This class is an abstract class
abstract class doing children: bound by all subclasses must implement to be abstractmethod decoration method name
to our code specifies specification
features: an abstract class can not be instantiated, but as a specific class specifications
abstract class look like

class 类名(metaclass = 'ABCMeta'):

    @abstractmethod
    def 规定的方法名(self):pass

    @abstractmethod
    def 规定的方法名(self):pass

    @abstractmethod
    def 规定的方法名(self):pass

Interface classes

Class only single inheritance, so the abstract class can only be all subclasses only a specification
java None of multiple inheritance class
interfaces can inherit multi-
specific syntax is no interface in python where
we just kind of multiple inheritance by imitating the effect of the interface

from abc import ABCMeta,abstractmethod
class NormalAnnimal(metaclass=ABCMeta):
    @abstractmethod
    def eat(self):pass

    @abstractmethod
    def drink(self):pass
class FlyAnimal(metaclass=ABCMeta):
    @abstractmethod
    def fly(self):pass

class SwimAnimal(metaclass=ABCMeta):
    @abstractmethod
    def swim(self):pass

class WalkAnimal(metaclass=ABCMeta):
    @abstractmethod
    def walk(self):pass

And abstract class, the base class and more decorative methods, subclass must to achieve it, in java, the method of the base class defined, usually just defined, can not be achieved, and in python is not as restrictions, possible to achieve, but are generally only defined method, to achieve in the subclass.

to sum up:

  • An abstract class is a single inheritance norms
  • Interface class is multiple inheritance norms

in java

  • All methods are defined inside the interface can not write the specific implementation pass
  • All internal abstract methods defined inside abstract class that can complete some simple code

Polymorphism

Polymorphism refers to a class of things there are many forms
of animals have a variety of forms: human, dog, pig

import abc
class Animal(metaclass=abc.ABCMeta): #同一类事物:动物
    @abc.abstractmethod
    def talk(self):
        pass

class People(Animal): #动物的形态之一:人
    def talk(self):
        print('say hello')

class Dog(Animal): #动物的形态之二:狗
    def talk(self):
        print('say wangwang')

class Pig(Animal): #动物的形态之三:猪
    def talk(self):
        print('say aoao')

File has a variety of forms: text files, executable files

import abc
class File(metaclass=abc.ABCMeta): #同一类事物:文件
    @abc.abstractmethod
    def click(self):
        pass

class Text(File): #文件的形态之一:文本文件
    def click(self):
        print('open file')

class ExeFile(File): #文件的形态之二:可执行文件
    def click(self):
        print('execute file')

Polymorphism

peo=People()
dog=Dog()
pig=Pig()

#peo、dog、pig都是动物,只要是动物肯定有talk方法
#于是我们可以不用考虑它们三者的具体是什么类型,而直接使用
peo.talk()
dog.talk()
pig.talk()

#更进一步,我们可以定义一个统一的接口来使用
def func(obj):
    obj.talk()

Ducks type
Python advocates duck type, that is, 'If it looks like, sounds like and walks like a duck, then it is a duck'

# 二者都像鸭子,二者看起来都像文件,因而就可以当文件一样去用
class TxtFile:
    def read(self):
        pass

    def write(self):
        pass

class DiskFile:
    def read(self):
        pass
    def write(self):
        pass

to sum up:

# 鸭子类型
    # python当中写程序的一种特殊的情况
    # 其他语言中 正常的我们说一个数据类型具有某个特点,通常是通过继承来实现
        # 继承迭代器类,来证明自己本身是个迭代器
        # 继承可哈希的类,来证明自己本事是可哈希的
    # 但是所有的这些都不是通过继承来完成的
        # 我们只是通过一种潜规则的约定,如果具有__iter__,__next__就是迭代器
        # 如果具有__hash__方法就是可哈希
        # 如果具有__len__就是可以计算长度的
    # 这样数据类型之间的关系并不仅仅是通过继承来约束的
    # 而是通过约定俗成的关系来确认的

# 多态
    # 在传递参数的时候,如果要传递的对象有可能是多个类的对象
        # 我们又必须在语言中清楚的描述出到底是那一个类型的对象
        # 我们就可以使用继承的形式,有一个父类作为这些所有可能被传递进来的对象的基类
        # 基础类型就可以写成这个父类
        # 于是所有子类的对象都是属于这个父类的
    # 在python当中,因为要传递的对象的类型在定义阶段不需要明确,所以我们在python中处处都是多态
        # 数据的类型不需要通过继承来维护统一

Guess you like

Origin www.cnblogs.com/yangchangjie150330/p/10615522.html