Python recursion and object-oriented first knowledge and programming thought

Source: Internet
Author: User
Tags class definition

First, recursion

1. Definition:

Inside a function, you can call other functions. If a function calls itself internally, the function is a recursive function.

(1) Recursion is the invocation of itself in a process or function;
(2) When using a recursive strategy, there must be a definite recursive end condition called a recursive exit.

1 def Age (n): 2     if n ==1:   #条件判定3         return  #返回一个结果4     else:5         return (n-1) +2  #重复调用函数本身, The result of the operation is stored on the stack, followed by a call to the value. 6 Print (age (5))   #打印结果

Execution Result: 18

2. Advantages and Disadvantages: 

The advantage of recursive functions is that they are simple in definition and clear in logic. In theory, all recursive functions can be written in a circular way, but the logic of the loop is not as clear as recursion.

The disadvantage of recursion: recursive algorithm is inefficient in solving problems. In the process of recursive invocation, the system opens up a stack for each layer's return point, local quantity and so on. Too many recursion times can cause stack overflow and so on.

def func ():    print ("*******") func () func (    ) #执行结果 [Previous Line repeated 993 more times]*******  File "F:/py_ fullstack_s4/day26/recursive. Py ", line 8, in func*******    print (" ******* ") *******recursionerror:maximum recursion depth Exceeded while calling a Python object

3, recursive programming points of attention:

1. There must be a clear end condition.

2. Each time a deeper level of recursion is reached, the problem size should be reduced compared to the previous recursion.

3. Recursive efficiency is not high, too many recursive hierarchy will lead to stack overflow (in the computer, function calls through the stack (stack) This data structure implementation, each time into a function call, the stack will add a stack of frames, whenever the function returns, the stack will reduce the stack frame. Because the size of the stack is not infinite, there are too many recursive calls, which can cause the stack to overflow.

4, here brings a new knowledge point: Dichotomy

Dichotomy, is a fast method of finding, time complexity is low, logic is easy to understand, in general, divided by 2 divided by 2 ...

He is mainly used in sequential sequence , the principle is that every time the original sequence is binary , gradually narrowing the search range of an algorithm. Applies to recursion, in loops, until the result is found.

#运用 the method of recursion and dichotomy, look for a value in the list data = [1, 3, 6, 7, 9, B, B, B, A,,, +, +, +, +, +, = Int (input ("ple        ASE input your want to find number: ") def search (num,data): If Len (data) > 1: #排除列表分割, only one element left #二分法 #     a = Int (len (data)//2) #将计算列表的长度, divided by 2 to take an integer mid_value = data[a] #取当前中间的值 if num > Mid_value:  #要找的值 greater than the middle value data = Data[a:] #将原列表从中间值往后, take out, build a new list search (num,data) #递归判断 elif num < mid_value: #要找的值 less than the middle value data = Data[:a] #将原列表开始到中间值, take it out and build a new list search (Num,data) #递归                         Judge Else: #正好是这个值 print ("Find it!!", num) return #打印 else:                     #判断列表分割, only one element is left if data[0] = = Num:print (' Find it!!%s '%data[0]) Else: #列表中没有这个值 print (' Not this num%s '%num) search (num,data) #执行结果: "Please input your want to find number : 18find it!! 18

Second, the functional programming introduction

1. Use Def to imitate the function of mathematics, pass a value, you have a result. The external state is not modified.
2, the code is very streamlined, directly resulting in very poor readability.

Third, object-oriented programming

1, the premise of bedding:

Everything in Python is an object, and Python 3 unifies the concept of classes and types, which are classes. For example: Int,str,list, etc...

In a programming language, you first have a class, and then you produce one object at a later date. And the opposite is true in real life.

Be clear: object-oriented programming is a programmatic approach that requires the use of "classes" and "objects" , so object-oriented programming is actually the use of "classes" and "Objects ."

  A class is a template that can contain the ability to create multiple functions that implement a custom function.

Objects are instances created from templates that can execute functions defined in a class through an instance (object)

2. Syntax:

1) Create Class: Class is the keyword, which indicates that classes * * * #创建类
2) Create object: The class name is followed by parentheses to assign the result to a variable x = * * () #创建对象

1 class Hello:  #任意定义一个类 2     camp = ' Hello World ' 3     def f (self): 4         print ("F") 5 H = Hello () # class instantiation 6 print (h) #打印 7  8 #执行结果: 9 <__main__.hello object at 0x00000000026c9630>

3. Classes and objects

1) What is an object:
Take the game example: League of Legends, each player to choose a hero, each hero has his own characteristics and skills, characteristics of data attributes, skills is the method of attributes, characteristics and skills of the combination of an object.

2) What is a class:
Extracts objects from a set of objects common characteristics, skills, constitute a class. A class is also a combination of features and skills , characterized by data and data shared by all objects, the skill is a function attribute and is a function attribute shared by all objects.

  ① Advantages: solve the extension of the program, the modification of an object, will be immediately reflected in the entire system
  ② Disadvantage: poor controllability, unable to predict the final result.
  Object-oriented programming is not the whole program. For software quality, object-oriented programming is only to solve the problem of extensibility.

Either DEF or class defines a function name. Class definition Classes Camp Camp attack (self) Skill nickname Nickname Init start, initial

3) How to use the class:
First, the instantiation of

  The instantiation of a class produces an instance (object). Can be understood as a class plus () to instantiate a virtual thing, to get a concrete existence of the value, called the instantiation of the class.

Class Garen:  #定义一个类    camp = ' Demacia ' def attack (self):    print (' attack ') G1 = Garen () #类的实例化, produces an object, You can invoke all the features (commonalities) that are included within the class. Print (G1)  #打印 # Execution Result: <__main__. Garen Object at 0x00000000028c9cc0>

 second, the class through the. (point) to refer to a feature (a variable of a class) and skill (a function of a class (a function within a class or a definition, a call or an incoming parameter))

Class Garen:    camp= ' Demacia '    def attack (self): print        (' attack ') print (Garen.camp)  #查看campprint ( Garen.attack)   #打印数据类型Garen. Attack (' Nihao ') #由于是调用有参函数, need to pass value # Execution result: Demacia<function garen.attack at 0x000000000229c950>attack

2, there are different objects, and in addition to the same sex also has characteristics. such as nickname!

Class Garen:    camp= ' Demacia '    def __init__ (self,nickname):        self.nick=nickname  #给实例自己定义一个别名, incoming by external # G1.nick = ' Bush lun '    def attack (Self,enemy):        # print ('----------> ', Self.nick) #g1. Nick        print ('%s attack%s ') % (Self.nick,enemy)) G1=garen (' Bush lun ') #类实例化, class Garen trigger call _init_ #Garen. _init_ (self, ' NB ') g2=garen (' Liu Xia ') print (G1.nick) G1.attack (' Alex ') #执行结果: Bush Warren attack Alex

Self refers to himself.

Note: Instantiation of a class automatically triggers execution of the _INIT_ function within the class.

3, how to invoke the characteristics of the class and skills

Note: The binding method between the class and the object. Calling the binding method, Python automatically passes the value, passing the caller itself as a parameter to self, the first value.
Print (Gi.attack) #调用绑定方法, class bound to G1
Print (Garen.attack) #函数

Class Garen:    camp= ' Demacia '    def __init__ (self,nickname):        self.nick=nickname  #给实例自己定义一个别名, incoming by external # G1.nick = ' Bush lun '    def attack (Self,enemy):        # print ('----------> ', Self.nick) #g1. Nick        print ('%s attack%s ') % (Self.nick,enemy)) G1=garen (' Bush lun ') #类实例化, class Garen trigger call _init_ #Garen. _init_ (self, ' NB ') g2=garen (' Liu Xia ') print (G1.nick)  #昵称print (G1.camp)  #阵营print (g1.attack)  #打印 View binding method Print (Garen.attack)  # Print function # execution result: Bush-lun-demacia< Bound method Garen.attack of <__main__. Garen object at 0x0000000002299d68>><function garen.attack at 0x000000000229c9d8>

Garen.attack (parameter) # Call a function, need to pass the argument
G1.attack (' alex ') #self = G1;enemy = ' Alex ' If the function has more than one value, the other parameters are passed in when the value is assigned.

Print (G1.nick)

As long as the object is triggered, the call will automatically pass the value to the calling function, passing itself to the first argument self. If the function has more than one value, it will pass in the other parameters when the value is assigned.

Class Garen:    camp= ' Demacia '    def __init__ (self,nickname):        self.nick=nickname  #给实例自己定义一个别名, incoming by external # G1.nick = ' Bush lun '    def attack (Self,enemy):        # print ('----------> ', Self.nick) #g1. Nick        print ('%s attack%s ') % (Self.nick,enemy)) G1=garen (' Bush lun ') #类实例化, class Garen trigger call _init_ #Garen. _init_ (self, ' NB ') g2=garen (' Liu Xia ') print (G2.nick) Print (G2.camp) #执行结果: Liu Ying Demacia

Three, Summary:
1, class: One: Instantiation, two: reference name (class name. variable name, class name, function name) get a memory address, plus () to run.

2. Instance (object): Reference name (instance name, variable of class, instance name.) Bind method, instance name. Instance's own variable name)

3. Class:
 Advantages : It solves the extensibility of the program and modifies an object, which is immediately reflected in the whole system.
 Cons: poor controllability, unable to predict the final result.
Object-oriented programming is not all. For software quality, object-oriented programming is only to solve the problem of extensibility.

In Python, a variable is used to represent a feature and a function to represent a method, so a class is a combination of a variable and a function, and the object is a combination of a variable and a method (a function that points to a class).

4. Class attributes: Features (variables) and methods (functions)

5, The class has two methods: 1. class instantiation; 2. Property Reference
1. 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.
2. Attribute references:
Class name. method

6. Objects are also known as instances

Object properties: The object itself has its own characteristics (variables)

Object has only one usage: Property reference

7. Namespaces for classes and namespaces for objects

Creating a class creates a namespace for a class that holds the attributes defined in the class: Features (data) and methods (functions)
Creating an object, and instantiating the class, creates a namespace for the class that holds the properties of the object.

Note: The object is the instantiation of the class, the class completes the instantiation of the operation of the class has been bound to the object, the object call method will now find their own namespace, find not to go to the class namespace to find, and then find not to throw an exception. It's not going to look for a global definition.

View the namespace class name for the class. _dict_
View the Namespace object name of the object. _dict_

The core of the binding method is ' bind ', uniquely bound to a certain object

Can be called: check
Print (Garen.camp) #查

Can change: change
garen.camp= ' aaaaaa ' #改
Print (Garen.camp)

Can be deleted: delete
Del Garen.camp #删除
Print (Garen.camp)

You can add: increase
Garen.x=1 #增加特征
Print (garen.x)

About Objects (instances)

Can be called: check
G1=garen (' Alex ')
Print (G1.nick) #查

Can change: change
g1.nick= ' ASB ' #改
Print (G1.nick)

Can be deleted: delete
Del G1.nick
Print (G1.nick) #删

can increase: increase
g1.sex= ' Female '
Print (G1.sex) #增加

Four, object-oriented software development:

Divided into five parts:

1. Object-oriented analysis (oriented ANALYSIS,OOA):
Product Manager investigates the market, examines, and clarifies the use and application scenarios of the software.
2, Object-oriented design (object oriented Design,ood):
According to the requirements, each part of the specific design, such as: The design of the class
3, Object-oriented programming (Object oriented Programming,oop):
Programming the design into code
4, Object-oriented testing (object oriented Test,oot):
Test the written code to find errors and correct them. Object-oriented testing is an object-oriented approach to testing, with classes as the basic unit for testing.
5, Object-oriented maintenance (object oriented soft MAINTENANCE,OOSM):
Solve problems that occur during the user's use of the product or add new functionality.

Object-oriented Programming idea:
1, when the design, must be clear application scenarios

2. When defining classes by object analysis, we cannot find common features and skills without forcing

Python recursion and object-oriented first knowledge and programming thought

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.