Python Object-oriented section simple collation

Source: Internet
Author: User

Object-oriented VS process-oriented
Process oriented
The core of process-oriented program design is process (pipeline thinking)
Advantages:
Greatly reduces the complexity of writing programs
Disadvantages:
A whole process (pipelining) can only solve one problem, and if the problem changes, the code is almost completely rewritten.
Application Scenarios:
Once you've done a few basic changes, the famous examples are Linux kernel, git, and Apache HTTP server.
More suitable for waterfall flow in the product development environment


Object oriented
The core of object-oriented program design is Object (God-type thinking)
The advantages are:
Resolves the extensibility of the program

Disadvantages:
Poor controllability, inability to handle a problem as well as process-oriented and precise
Application Scenarios:
Frequently changing requirements of software, general requirements of the changes are concentrated in the user layer, Internet applications, enterprise internal software, games, etc.
Better suited for Agile development (iterative) product development environments

Class
Basic format
Class Person: #定义一个人类

role = ' person ' #人的角色属性都是人

def __init__ (self, name):
Self.name = name # Each character has its own nickname;

def walk (self): #人都可以走路, that is, there is a way to walk, also known as dynamic properties
Print ("Person is walking ...")

Two kinds of functions of the class:
Attribute references and instantiation
Print (Person.role) #查看人的role属性
Print (Person.walk) #引用人的走路方法, note that this is not a call to the

Instantiation:
The class name parentheses are instantiated, which automatically triggers the operation of the __INIT__ function, which can be used to customize the characteristics of each instance.
The process of instantiating is a class-to-object procedure

Syntax: Object name = class Name (parameter)
Egg = person (' Egon ') #类名 () is equal to executing person.__init__ ()
An object is returned when the __init__ () is executed. This object is similar to a dictionary and has some properties and methods that belong to the person itself.

viewing properties and calling methods
Print (egg.name) #查看属性直接 object name. Property name
Print (Egg.walk ()) #调用方法, object name. Method Name ()

Self
Automatically passes the object/instance itself to the first parameter of __init__ when instantiated

Supplement to class attributes
A: Where do the properties of the class we define are stored? There are two ways of viewing
Dir (class name): A list of names is isolated
The class name. __DICT__: A dictionary is found, key is a property name, value is a property value

Second: Special class properties
Class name The name of the __name__# class (string)
The document string for the class name. __doc__# class
Class name the first parent class of the __base__# class
Class name The tuple that consists of all the parent classes of the __bases__# class
Class name. Dictionary properties for the __dict__# class
Class name. The module where the __module__# class is defined
Class name the class that corresponds to the __class__# instance (in the modern class only)


Object
Object is an example of a class that actually exists, that is, an instance

Object-oriented definition and fixed formatting of calls
Class Name:
def __init__ (self, parameter 1, parameter 2):
Self. Properties of the Object 1 = parameter 1
Self. Properties of the Object 2 = parameter 2

def method name (self):p

Def method Name 2 (self):p

Object name = Class name (#对象就是实例), which represents a specific thing
#类名 (): Class name + parenthesis is the instantiation of a class, equivalent to calling the __init__ method
#括号里传参数, the parameter does not need to pass self, and the other corresponds to the formal parameter one by one in Init
#结果返回一个对象
Object name. The object's property 1 #查看对象的属性, directly with the object name. Property name
The name of the object. Method Name () #调用类中的方法, directly with the object name. Method Name ()


namespace of class namespace and object, instance namespaces
Creating a class creates a namespace for a class that stores all the names defined in the class, called Properties of the class
Where the data properties of a class are shared to all objects
The dynamic properties of a class are bound to all objects.

Two properties of the class:
Static properties and Dynamic properties
A static property is a variable that is defined directly in the class
A dynamic property is a method defined in a class


Combination
The important way of software reuse in addition to inheritance there is another way, namely: the combination
A combination refers to a class in which an object of another class is used as a data property, called a combination of classes
When the classes are significantly different, and the smaller classes are the components needed for larger classes, the combination is better



Object-oriented three main features: inheritance, encapsulation, polymorphism
Inherited
Inheritance is a way of creating new classes in Python, where a new class can inherit one or more parent classes, which can be called a base class or a superclass, and a new class is called a derived class or subclass.
Single-Inheritance and multiple-inheritance instances
Class ParentClass1: #定义父类
Pass

Class ParentClass2: #定义父类
Pass

Class SubClass1 (PARENTCLASS1): #单继承, the base class is ParentClass1, and the derived class is subclass
Pass

Class SubClass2 (PARENTCLASS1,PARENTCLASS2): #python支持多继承, separate multiple inherited classes with commas
Pass


Inheritance and abstraction
Inherited:
is based on abstract results, through the programming language to achieve it, it must be through the process of abstraction, in order to express the abstract structure through inheritance.
Abstract:
Only in the process of analysis and design, an action or a skill, through abstraction, can get the class

Inheritance and re-usability
Derived

Super
In Python3, a subclass's method of executing the parent class can be used directly with the Super method.


The relationship between the derived class and the base class is established through inheritance, which is a ' yes ' relationship, such as a horse in a white horse and a human being an animal.
When there are many identical functions between classes, extracting these common functions into a base class is better with inheritance, for example, a professor is a teacher.

Abstract classes and Interface classes
Interface class
There are two uses of inheritance:
One: Inherit the methods of the base class and make your own changes or extensions (code reuse)
Two: Declare a subclass compatible with a base class, define an interface class interface, the interface class defines some interface names (that is, the function name) and does not implement the functions of the interface,
Subclasses inherit the interface class and implement functionality in the interface

The first meaning of inheritance is not very large, and often harmful. Because it causes the subclass to be strongly coupled to the base class.
The second meaning of inheritance is very important. It is also called "Interface inheritance."
Interface inheritance is essentially a requirement "to make a good abstraction, which prescribes a compatible interface so that external callers do not have to care about the specifics,
All objects of a particular interface are implemented in a non-discriminatory process "-this is called Normalization in program design.
Normalization allows high-level external users to handle the collection of objects that are compatible with all interfaces without distinction

Dependency Inversion principle:
High-level modules should not rely on the lower layers, both should rely on their abstraction; abstractions should not be dependent on details; Details should be dependent on abstraction.
In other words, to program for the interface, not to implement programming

Abstract class
Abstract classes can only be inherited, not instantiated

The essence of an abstract class is also a class, which refers to the similarity of a set of classes, including data properties and function properties, and interfaces only emphasize 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
In Python, there is no such thing as an interface class, and we should have some basic concepts, even if we don't define interfaces through specialized modules.


Multiple inheritance issues
In the process of inheriting abstract classes, we should try to avoid multiple inheritance;
When inheriting interfaces, you should inherit more interfaces.
Interface Isolation principle:
Use multiple specialized interfaces without using a single total interface. That is, clients should not rely on interfaces that are not needed.

Implementation of the method
In abstract classes, we can make basic implementations of some abstract methods;
In the interface class, any method is just a specification, and the specific function requires subclasses to implement



Inherited
Classes that inherit multiple classes have two ways of finding their way: depth first and breadth first

Classic class-------Depth first
New class-------Breadth first
Depends on whether the current class or parent class inherits the object class

The role of inheritance:
Reduce the reuse of code
Improve code Readability
Canonical Programming mode


Polymorphic
Polymorphism refers to a class of things that have many forms
Polymorphism
What is polymorphic dynamic binding (sometimes called polymorphism when used in an inherited context)
Polymorphism refers to the use of instances without regard to instance types


Packaging
Hides the properties and implementation details of an object, providing public access only to the outside.
Advantages:
Isolate changes, ease of use, improve reusability, and improve security
Packaging principles
To hide the content that does not need to be provided externally;
Hides properties, providing public methods for accessing them.


Private variables and private methods
Hide a property (set to private) in Python, starting with a double underscore

Property
Classmethod
Staticmethod



Object-oriented Advanced
Isinstance (obj,cls) checks if obj is an object of class CLS
Issubclass (sub, super) check if the sub class is a derived class of super class


Reflection
Manipulate object-related properties in the form of strings. All things in Python are objects (you can use reflection)
Hasattr detect if a property is included
GetAttr Getting properties
SetAttr Setting properties
Delattr Deleting properties


Changing the object's string display __str__,__repr__
Self-Customizing formatted string __format__

__del__
destructor, which automatically triggers execution when the object is freed in memory. No need to define, no need to care about Python memory allocation and release

Item series
__getitem__
__setitem__
__delitem__

__new__

The __call__ object is appended with parentheses to trigger execution.

__len__

__hash__

__eq__








Python Object-oriented section simple collation

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.