8 Python abstract class

Source: Internet
Author: User
Tags define abstract

1, abstract class--similar interface

The concept of interface:

The way you provide the user with the ability to invoke your own function \ method \ portal,

1.1. Interface interface in Java

=================The first part: The interface in the Java language shows the meaning of the interface well: Ianimal.java/** Features of Java's interface interface:* 1) is a collection of functions, not a function * 2) interface for interaction, all functions are public, that is, other objects can be manipulated  * 3) The interface only defines functions, but does not involve function implementations  * 4) These functions are related, are animal related functions, but photosynthesis is not suitable to put into the ianimal inside the * *Package Com.oo.demo;public interface IAnimal {public void eat ();     public void run ();     public void sleep (); public void Speak ();}=================Part II: Pig.java: Pig "class design, the implementation of the Iannimal interface package Com.oo.demo;publicclassPig implements ianimal{//each of the following functions requires a detailed implementation of public void Eat () {System.out.println ("Pig like to eat grass"); } public void Run () {System.out.println ("Pig run:front legs, back legs"); } public void Sleep () {System.out.println ("Pig sleep hours every day"); } public void Speak () {System.out.println ("Pig can not speak"); }}=================Part III: Person2.java/**The realization of the IAnimal "people", there are several points to explain:* 1also implemented the IAnimal interface, but "man" and "pig" implementation is not the same, in order to avoid too much code to affect reading, the code here is simplified to one line, but the output of the content is different, the actual project in the same interface of the same function point, the implementation of the class is not identical* 2) This is also the "person" class, but it is not the same as the class "people" given in the previous class, because the same logic concept, in different scenarios, has the properties and functions are completely dissimilar */Package Com.oo.demo;publicclassPerson2 implements IAnimal {public void Eat () {System.out.println ("Person like to eat meat"); } public void Run () {System.out.println ("Person run:left leg, right leg"); } public void Sleep () {System.out.println ("Person sleep 8 hours every dat"); } public void Speak () {System.out.println ("Hellow World, I am a person"); } }

1.2, why to use the interface
The interface extracts a group of common functions that can be used as a collection of functions. Then let the subclass implement the functions in the interface. The significance of this is normalization, what is called normalization, that is, as long as it is based on the same interface implementation of the class, then all of these classes produce objects in use, from the usage of the same. the benefit of normalization is that normalization allows the user not to care about what the object's class is, but only needs to know that these objects have some functionality, which greatly reduces the user's difficulty in using it.
Normalization allows high-level external users to handle the collection of objects that are compatible with all interfaces without distinction
Just like the universal file concept of Linux, everything can be processed as a file, without worrying about whether it's memory, disk, network, or screen (of course, for the underlying designer, of course, you can distinguish between "character devices" and "block devices", and then make a targeted design: to what extent, depending on demand).
Again for example: We have a car interface that defines all the functions of the car, then by the Honda Car class, Audi car class, Volkswagen class,

They all realized the car interface, so it is good to do, we just have to learn how to drive a car, then whether it is Honda, or Audi, or the public we will open, open when there is no need to care about what kind of car I drive, operating methods (function calls) are the same
2. Imitation interface

In Python there is no keyword called interface, if you want to imitate the concept of an interface

Third-party modules available: Http://pypi.python.org/pypi/zope.interface

Inheritance can also be used, in fact, there are two uses of inheritance

One: Inheriting the method of the base class and making its own changes or extensions (code reuse): In practice, this use of inheritance is not very significant, and often harmful. Because it causes the subclass to be strongly coupled to the base class.

Two: Declare a subclass is compatible with a base class, define an interface class (imitate Java interface), the interface class defines some interface name (that is, the function name) and does not implement the functions of the interface, subclass inherits the interface class, and implements the function in the interface

classInterface: # defines an interface interface class to mimic the concept of an interface, in Python there is no interface keyword to define an interface.     defRead (self):#Fixed interface function Read        Pass    defWrite (self):#defining an interface function write        PassclassTXT (Interface):#text that implements read and write specifically    defRead (self):Print('How to read text data')    defWrite (self):Print('How to read text data')classSata (Interface):#disk, specifically implemented read and write    defRead (self):Print('How to read hard disk data')    defWrite (self):Print('How to read hard disk data')classProcess (Interface):defRead (self):Print('method of reading process data')    defWrite (self):Print('method of reading process data')

The above code just looks like interface, actually does not play the role of interface, subclass can not implement interface completely, this uses the abstract class

3. This section focuses on---Abstract class 3.1, what is abstract class

Like Java, Python also has the concept of abstract classes but also requires the use of a module implementation, the abstract class is a special class, its special is that can only be inherited, can not be instantiated

3.2, why should have abstract class

If a class extracts the same content from a bunch of objects, the abstract class extracts the same content from a bunch of classes, including data properties and function properties.

For example, we have banana class, Apple class, Peach class, from these classes to extract the same content is the abstract fruit of the class, you eat fruit, either to eat a specific banana, or to eat a specific peach ... You can never eat something called a fruit.

From a design perspective, if a class is abstracted from a real object, the abstract class is based on class abstraction.

From an implementation perspective, abstract classes differ from ordinary classes in that abstract classes can only have abstract methods (without implementing functionality), that classes cannot be instantiated, can only be inherited, and subclasses must implement abstract methods. This is a bit similar to the interface, but it's actually different, and the answer is coming soon.

4. Implement abstract classes in Python
#All DocumentsImportAbc#implementing abstract classes with ABC modulesclassAll_file (metaclass=ABC. Abcmeta): All_type='file' @abc. Abstractmethod  # defines abstract methods without implementing functionality     defRead (self):'subclasses must define read functionality'        Pass@abc. Abstractmethod#define abstract methods without implementing functionality    defWrite (self):'subclasses must define write functions'        Pass#class Txt (all_file):#Pass##t1=txt () #报错, subclasses do not define abstract methodsclassTXT (All_file):#subclasses inherit abstract classes, but must define the read and write methods    defRead (self):Print('How to read text data')    defWrite (self):Print('How to read text data')classSata (All_file):#subclasses inherit abstract classes, but must define the read and write methods    defRead (self):Print('How to read hard disk data')    defWrite (self):Print('How to read hard disk data')classProcess (All_file):#subclasses inherit abstract classes, but must define the read and write methods    defRead (self):Print('method of reading process data')    defWrite (self):Print('method of reading process data') Wenbenwenjian=Txt () Yingpanwenjian=Sata () Jinchengwenjian=Process ()#so everyone is normalized, that is, the thought of all documents.Wenbenwenjian.read () yingpanwenjian.write () Jinchengwenjian.read ( )Print(Wenbenwenjian.all_type)Print(Yingpanwenjian.all_type)Print(Jinchengwenjian.all_type)
4.1. Abstract class and interface

The essence of an abstract class is also a class, which refers to the similarity of a set of classes, including data attributes (such as All_type) and function properties (such as read, write), while the interface only emphasizes the similarity of function properties.

Abstract Classes are a direct concept between classes and interfaces, with some of the features of classes and interfaces that can be used to implement a normalized design

4.2. ABC module, PYTHON support module for ABC, defines a special metaclass-- Abcmeta and some adorners- @abstractmethod and @ Abstarctproperty.
Import ABC class A (metaclass=ABC. Abcmeta):    @abc. Abstractmethod#  defines an abstract method without implementing the function    def  Read (self):         pass    @abc. Abstarctproperty#  defining abstract Properties
4.3. Examples
  by defining abstract classes, subclasses inherit abstract classes, handle class normalization, and if you want to invoke the same function as an abstract class, you must be consistent with the abstract class or else an error
Canonical subclass

ImportABCclassAnimal (metaclass=ABC. Abcmeta): @abc. AbstractmethoddefRun (self):Pass@abc. AbstractmethoddefEat (self):Passclasspeople (Animal):defRun (self):Print('people is walking') defEat (self):Print('people is eating')classDog (people):defRun (self):Print('Dog is walking') defEat (self):Print('Dog is eating')classPig (people):defRun (self):Print('Pig is walking') defEat (self):Print('Pig is eating') People1=people () Dog1=Dog () pig1=Pig () People1.run () Dog1.run () Pig1.run ( )
4.4. Description of abstract class

Can not be instantiated, can only be inherited: Aminal is an abstract class in the title, can not be instantiated such as animal=aminal ()

Pros: Normalize subclasses to reduce the complexity of use

8 Python abstract class

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.