Object-oriented programming of Python

Source: Internet
Author: User
Tags class definition

First: Design ideas and development process (understanding)

1940 ago: machine-oriented programming
The earliest is the use of machine language programming, that is, directly using binary code to represent the machine can recognize the instructions and data.
Advantage: Machine language is executed directly by machine, speed is fast
Cons: Very difficult to write, and not easy to modify.

assembly Language : The use of mnemonic symbols instead of the operation code of the machine instruction, with the address symbol or label instead of the address of the instruction or operand
Advantage: Easier to write binary code than machine language
Disadvantage: assembly language is essentially a machine-oriented language, difficult to write, error prone

After leaving the machine: process-oriented programming
Process-oriented structured programming emphasizes the abstraction of functionality and the modularity of the program, which considers the problem-solving process as a process, such as the C language
Advantages: Easy to operate on the underlying hardware, memory, CPU, etc.
Disadvantages: Not easy to expand, write code, debugging more Trouble

Software crisis for the first time: structured programming
Adopt the guiding ideology of "top down, gradual refinement and modularization". Structured programming is still a process-oriented design concept, but through "top-down, gradual refinement, modularization" method, the complexity of software is controlled in a certain range, thereby reducing the complexity of software development on the whole
1960 Outbreak, background: Due to software quality is low, project can not be completed on schedule, project seriously overrun, because the software caused by major accidents often occur, mainly in the complexity
1968 first structured programming language Pascal was born
1970 becomes the mainstream of software development

Second software crisis: Object-oriented programming
Root cause: Software productivity lags far behind the development of hardware and business.
Mainly embodied in ' extensibility ' and ' maintainability '
As early as 1967, the Simula language proposed object-oriented, the second crisis promoted the object-oriented development
The 1980s era, thanks to C + +, and later java,c# the object-oriented to the peak, has now become the mainstream development ideas

Second: What is object-oriented programming

First of all, in this talk about what is process-oriented design :

Process-oriented program design is the core of the process, the process is the steps to solve the problem. Process-oriented can be understood as a line

The advantages are: greatly reducing the complexity of the program

The disadvantage is: a set of pipeline or process is to solve a problem, if the production line of bread can not produce buns, even if it can, also have to be big change, change a component, reaching.

Application scenario: Once you have completed a very rarely changed scenario, the notable examples are Linux kernel, git, and Apache HTTP server.

Object-oriented design:

Object-oriented program design is the core of objects, objects can be understood as features, attributes, etc.

The advantage is that it solves the extensibility of the program. A single modification of an object is immediately reflected in the entire system, such as the character of a character parameter in the game and the ability to modify it easily.

Cons: Poor controllability, inability to process-oriented programming pipelining can accurately predict the problem of the processing process and results, the object-oriented program once started by the interaction between the object to solve the problem, even God can not predict the end result.

Application scenario: frequently changing requirements of the software, the general needs of the changes are concentrated in the user layer, Internet applications, enterprise internal software, games, etc. are the object-oriented programming of the good place

Third: Classes and objects

Object-oriented concepts are classes (class) and instances (Instance), and it is important to keep in mind that classes are abstract templates, and instances are specific "objects" that are created from classes, each with the same method, but the data may be different.

Classes: The combination of data and functions, called properties of a class

Class:

Definition of the class:

class Garen:    # defines the class of heroes Galen, different players can use it to instantiate their own heroes;    camp='demacia'  # All Players ' Heroes (Galen's) faction are demacia;    def __init__ # Galen Hero's name, attack, health        Self.nickname=nickname  # alias        self.aggrv=aggresivity       # attack         self.life_value=life_value   # Health Value

Two functions of a class: instantiation and Attribute reference

#!/usr/bin/env python#-*-coding:utf-8-*-classGaren:camp='Demacia'    def __init__(self,nickname,aggresivity,life_value): Self.nickname=Nickname SELF.AGGRV=aggresivity Self.life_value=Life_valuedefAttack (Self,enemy): #攻击技能, Enemy is the enemyPrint('is attacking', Self,enemy)#function One of the class: instantiation (__init__ and self)
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.
G1=garen ('Bush LUN', 80,120)#garen.__init__ (G1, ' Bush Lun ', 80,120) #g1 =self,nickname= ' Bush lun ', aggresivity=80,life_value=120
#实例调用
G1.attack (3) #Garen. Attack (G1, ' a ')
#输出结果:
#is attacking <__main__. Garen Object at 0x0000000002679c50> 3

 #   class function Two: Property Reference (class name. property), including data properties and function Properties  Span style= "color: #008000;" >#   print   (Garen.camp)   #输出结果: Demacia  ##  Span style= "color: #008000;" > function properties:  print  (Garen. )  print   (garen.attack)  #   output result:  #  <function garen.__init__ at 0x000000000252b840>  #  <function garen.attack at 0x000000000252b8c8>  

The properties of the class are supplemented by:

A: Where do the properties of the class we define are stored? There are two ways to view Dir (class name): A Name list class name is detected.__dict__: A dictionary is found, key is the property name, value is the attribute two: Special Class attribute class name.__name__#the name of the class (string)The class name.__doc__#the document string for the classThe class name.__base__#the first parent class of a class (speaking of inheritance)The class name.__bases__#a tuple of all the parent classes of the class (speaking of inheritance)The class name.__dict__#Dictionary properties of the classThe class name.__module__#module where the class definition residesThe class name.__class__#class for instance (in modern class only)
Object:

Talk about the object individually, with the previous example

G1=garen (' Bush lun '# class instantiation gets G1 this instance, based on the instance to see the object

Instance/object has only one property:

# for an instance, there is only one function: Property Reference, the instance itself has only data properties Print (G1.nickname) Print (G1.AGGRV) Print (g1.life_value) output: Bush lun 80120

Object additions:

View instance properties are also dir and built-in __dict__ two ways special instance properties __class__ __dict__

The object/instance itself has only data properties, but the Python class mechanism binds the function of the class to the object, called the object's method, or is called a binding method

# instances can call the class's data properties and function Properties Print (g1.camp)        Print (G1.attack)    # Object Binding method
# Output Result:
# Demacia
# <bound method Garen.attack of <__main__. Garen Object at 0x0000000002269cc0>>
# class invocation: equivalent to a function Garen.attack#  output:# is attacking 1 2
Interactions between objects:
classGaren:camp='Demacia'    def __init__(self,nickname,aggresivity,life_value): Self.nickname=Nickname SELF.AGGRV=aggresivity Self.life_value=Life_valuedefAttack (Self,enemy):Print('is attacking', Self,enemy)classRiven:camp='Noxus'    def __init__(self,nickname,aggresivity,life_value): Self.nickname=Nickname SELF.AGGRV=aggresivity Self.life_value=Life_valuedefAttack (Self,enemy):Print('is attacking', Self,enemy) Enemy.life_value-=self.aggrv#G1.LIFE_VALUE-=R1.AGGRV kills Raven's health based on Galen's attack.G1=garen ('Bush LUN', 80,100) R1=riven ('Raven', 60,200)Print(G1.life_value) r1.attack (G1)Print(g1.life_value) output results:100 isAttacking <__main__. Riven Object at 0x00000000021a9e10> <__main__. Garen Object at 0x00000000021a9dd8>40

Namespace of the class:

Creating a class creates a namespace for a class that stores all the names defined in the class, called Properties of the class

Class has two properties: Data Properties and Function properties

Where the data properties of a class are shared to all objects

Print (ID (g1.camp)) Print (ID (garen.camp)) output results:3457544834575448

The function properties of a class are bound to all objects:

Print (ID (g1.attack)) Print (ID (garen.attack)) output results:3183904840155336

Summary: creating an Object/instance creates an object/instance namespace that holds the name of the object/instance, called the object/instance property

Find Camp in Garen, will first find from the __init__, camp, if not will be in the class to find, if not yet, go to the parent class to find, always put all the parent class to find out, not yet, will throw an exception.

IV: Inheritance and derivation

Object-oriented programming of Python

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.