I want to learn Python secretly, and then shock everyone (the next day)

Insert picture description here

The title is not intended to offend, but I think this ad is fun
. Take the above mind map if you like it. I can’t learn so much anyway.

Preface

Early review: I want to learn Python secretly, and then stun everyone (day one). The
above article wrote some basic knowledge of Python, from data types to four arithmetic operations, to branches and loops.

So today, we will look at the more abstract functions and classes. If you are not very familiar with the basics, you can solidify the foundation. After all, the foundation is not honest, it is very dangerous.

本系列文默认各位有一定的C或C++基础,因为我是学了点C++的皮毛之后入手的Python,这里也要感谢齐锋学长送来的支持。
本系列文默认各位会百度,会用在线编译器,因为我是突击学Python的,之前的编译环境都删了,但是吧,我发现在线编译是真的爽,浪费那时间去搭那环境干啥,学好了Python,会差那点请人搭环境的钱吗?

我要的不多,点个关注就好啦
然后呢,本系列的目录嘛,说实话我个人比较倾向于那两本 Primer Plus,所以就跟着它们的目录结构吧。

本系列也会着重培养各位的自主动手能力,毕竟我不可能把所有知识点都给你讲到,所以自己解决需求的能力就尤为重要,所以我在文中埋得坑请不要把它们看成坑,那是我留给你们的锻炼机会,请各显神通,自行解决。

Okay, let's move on to the topic.


The bottleneck of programming learning

Let's talk a little bit more relaxed first, and I'll talk about those stubbornly boring ones.

Regardless of whether you have a foundation or no foundation; whether you have learned programming or mathematics; more or less will encounter hardships. For example, the first problem I encountered on the way of learning programming was function parameter transfer. Wow, I was very high-spirited at the time. After all, I was a C++ person who had passed 90 points and wanted to walk sideways. But on the first day of training in the company, when the teacher showed us (explained) a piece of code, the whole person gave me a daze. It was a structure as a data type parameter, and a bunch of such parameters. In the same function. . .

Then in another place, to be precise, in another file, I called this function. At that time, I was stunned. I even forgot to record the screen. I waited for the actual operation. . .
What to pass on? Where did it go? ? ? Fainted. . .

Okay, it's a long way off. You can hit the bottleneck you encountered in the comment area. Maybe your thinking and meditation, others already have a solution.

Let a mountain pass a mountain barrier, being able to understand the code is only the first step in the basics, you have to write it yourself. When writing by myself, it is easy to encounter various problems. The second hurdle is debugging.

If I talk too much, I will teach you these skills. In this article, we will first look at functions and classes, and then we will talk about sub-file projects, Debug, basic project design and architecture and other things. If you like, you can follow up.


Functions are not so scary

Initial function

Function? Anyone who has studied middle school mathematics knows functions.
This function is not the other function.

Functions are organized, reusable, and are used to implement a single or related code segment.
Functions can improve application modularity and code reuse. You already know that Python provides many built-in functions, such as print(). But you can also create a function yourself, which is called a user-defined function.

Define a function

A picture is worth a thousand words:
Insert picture description here

Example:

def math(x):
    y = 3*x + 5
    return y

This function is used to achieve: the evaluation of y = 3x+5, where x is the parameter, don’t worry, there are many rules here, listen to me slowly.

First of all, do you have a compiler, like pycharm, it doesn't matter, there are still many online compilers, like "Programming China", choose Python programming.
Take the above paragraph to compile it first, run it, and those who can’t run it can Baidu it.

After running, you will find that there is nothing at all. This is not a lie. Yes, this is not a lie. We didn’t call it, so naturally there is nothing.

Function rules

函数代码块以 def 关键词开头,后接函数标识符名称和圆括号(),括号后面要紧跟冒号,不然会报错。def就相当于告诉编译器:我这里是一个函数,你注意一下哈

任何传入参数必须放在圆括号中间,关于这个参数的规矩嘛:
1、在调用函数时,对函数进行参数传递必须与函数声明时的参数列表对应。
2、函数声明时可以声明默认参数,在函数调用时如果没有对默认参数进行传值,这默认参数使用预设值,默认参数要放在参数列表最右侧
3、函数外传参的参数数据类型须一一对应(有些可以强转,碧如floatint4、参数类型多种多样,并不局限于常见的intfloatstr等参数类型,也可以传类对象等

函数内容以冒号起始,并且缩进。

return [表达式] 结束函数,选择性地返回一个值给调用方。不带表达式的return相当于返回 None

对于函数的调用,直接输入函数名,并传入参数(这里不考虑跨文件)

Specifically, read more.

Example 2:

# 定义函数
def printme( str ):
   "打印任何传入的字符串"
   print(str)
   return
 
# 调用函数
printme("我要调用用户自定义函数!")
printme("再次调用同一函数")

Example 3:

def menu(appetizer, course):
    print('一份开胃菜:' + appetizer)
    print('一份主食:' + course)
menu('话梅花生','牛肉拉面')
def list(list1,list2):
    print('fast food:'+list1)
    print('slow food:'+list2)
list('宫保鸡丁','水煮鱼')

result:

一份开胃菜:话梅花生
一份主食:牛肉拉面
fast food:宫保鸡丁
slow food:水煮鱼

Example 4:

Default parameter method:

def menu(appetizer, course, dessert = '绿豆沙'):
    print('一份开胃菜:' + appetizer)
    print('一份主食:' + course)
    print('一份甜品:' + dessert)


menu('话梅花生','牛肉拉面')
menu('话梅花生','牛肉拉面','银耳羹')
#银耳羹对应参数dessert

result:

一份开胃菜:话梅花生
一份主食:牛肉拉面
一份甜品:绿豆沙
一份开胃菜:话梅花生
一份主食:牛肉拉面
一份甜品:银耳羹

Example 5:

Variable length parameter

Its format is special, it is an asterisk * plus the parameter name, and its return value is also special. Let's take a look at the following example.

def menu(*barbeque):
    return barbeque

order = menu('烤鸡翅','烤茄子','烤玉米')
#括号里的这几个值都会传递给参数barbeque

print(order)
print(type(order))

Result:
You will find that the function returns the result: ('roasted chicken wings','roasted eggplant','roasted corn'), we can use the type() function to know that this data type is called a tuple

Like a list, a tuple is an iterable object, which means that we can use a for loop to traverse it, and the code at this time can be written as:

def menu(*barbeque):
    for i in barbeque:
        print('一份烤串:' + i)

menu('烤香肠', '烤肉丸')        
menu('烤鸡翅', '烤茄子', '烤玉米')
# 不定长参数可以接收任意数量的值
一份烤串:烤香肠
一份烤串:烤肉丸
一份烤串:烤鸡翅
一份烤串:烤茄子
一份烤串:烤玉米

Global variables and local variables

Variables defined inside a function have a local scope, and variables defined outside a function have a global scope.

Local variables can only be accessed within the function in which they are declared, while global variables can be accessed within the scope of the entire program. When the function is called, all the variable names declared in the function will be added to the scope.

total = 0 # 这是一个全局变量
# 可写函数说明
def sum( arg1, arg2 ):
   #返回2个参数的和."
   total = arg1 + arg2 # total在这里是局部变量.
   print("函数内是局部变量 : ", total)
   return total
 
#调用sum函数
sum( 10, 20 )
print("函数外是全局变量 : ", total)

Output result:

函数内是局部变量 :  30
函数外是全局变量 :  0

I think about it again.

Oh, multi-function nesting.
Just like a matryoshka, there can be another function in a function.

In fact, this is easy to understand. Think about print. It is just a function. We often used print in other functions before.


Function small project

Write a small calculator that supports four arithmetic operations without parentheses. It is too difficult to write parentheses.

Insert picture description here


Things are gathered by "class"

What is a class? What is an object?
Today's high-level programming languages ​​have a threshold, that is, you have to be object-oriented programming, and object-oriented programming, you have to have class support.
So what is object-oriented programming? It is to describe the characteristics and functions of a type of affairs, such as human beings, then the object is human, and human characteristics and functions must be realized in this category.
feature:

没什么毛
两个肩膀扛一个脑袋
等等

skill:

直立行走
使用火
能写字
等等

Right, if you put these characteristics and skills together, you are human.


Let me talk about two more concepts, objects and instances: What is an object? This is the class you want to construct, and what is the model constructed. Take the human example above, it can be understood as the mold when Nuwa pinches people. , Nu Wa was squeezing the earth facing the object of'human'.
What is the instance? It is constructed through this class, and the stuff with all the characteristics and functions of the class can be understood as the real people that Nu Wa pinched out.

Class creation

Insert picture description here

Look at pictures and talk, a picture is worth a thousand words.

Class instantiation

Insert picture description here

Class call

Insert picture description here

Here, let’s sort out the one-stop service:
create a human being, he has two legs, he can run and jump, how to write? Write like this:

class People:
	leg = 2
	def run(self):
		print('他是一个人,他能跑')
	def jump(self):
		print('He is a man,he can jump')

lihua = People()
lihua.run()

Okay, there is still something I haven't made clear here, what exactly does Biru say about "self".

  1. Self, as the name implies. Well, let's see how to use it directly.
class People:
	leg = 2
	def run(self):
		print('他是一个人,他有%d条腿,所以他能跑',self.leg)
	def jump(self):
		print('He is a man,he can jump because of his %d legs',legs)

lihua = People()
lihua.run()

If you want to call the class attribute outside the class, we have to create an instance first, and then call it in the format of instance name.

So if we want to call the class attribute inside the class, and before the instance is created, we need a variable to replace the instance to receive data, this variable is the parameter self.

The role of self is equivalent to first occupying a place for the instance, and when the instance is created, it will "retire and retreat to the virtuous".

In the same way, if we want to call other methods within a class method, we also need to use self to represent the instance.

  1. Initialization method
    In C++, there is initialization of classes, so there must be some in Python classes. Let's take a look at chestnuts:

The format of defining the initialization method is def init (self), which is composed of init plus the left and right underscores (the abbreviation of initialize "initialization").
The function of the initialization method is: when each instance object is created, the code in the method will run automatically without calling it.

class People:
	def __init__(self):
		print('恭喜你,你造了个人')
lihua1 = People()

This is one kind, another kind

class People:
	def __init__(self,num):
		self.num = num
	def born()
		print('恭喜你,你获得了'+self.num+'个好朋友')
lihua2 = People()
lihua2.born()

Watershed, the difficulty is even higher

Class inheritance

What is inheritance, inheritance in C++ is still very fun, just like your father is a class, you inherit some of the characteristics and skills of your father, you can also have your own skills, this is inheritance.

Insert picture description here

Then let's implement what we said above:

class Father:
	skin = 'yellow'
	def clever():
		print('他是个聪明人')

class Son(Father):
	def strugle():
		print('他很努力')

lihua = Son()
lihua.clever()
print(lihua.skin)
lihua.strucle()

Multiple inheritance

A class can inherit multiple classes at the same time. The syntax is class A(B,C,D):

Here you can realize a person by yourself and inherit the advantages of your parents. For example, the father is smart, the mother is good-looking, he is smart and good-looking, and motivated.

Small tip: the principle of proximity: the closer to the parent of the subclass (that is, the farther to the left), the closer, the more priority it will be considered. When subclasses call properties and methods, they will first look for the parent class on the left, and then look for the right when they cannot find it.

Insert picture description here

Learn more:
Insert picture description here


Parent function override

Rewriting code is a modification of the parent class code in the subclass.

Simply give a chestnut, in fact, this is still a very important point:

class Father:
	skin = 'yellow'
	def clever():
		print('他的智商100')

class Son(Father):
	def clever():
		print('他的智商110')
	def strugle():
		print('他很努力')
lihua = Son()
lihua.clever()

Practical small project

Here, let's realize a short story of family heritage to consolidate what we have learned today:

He was in a privileged family. His grandfather started the gauze business from scratch. In his grandfather’s generation, the business expanded further, adding new pharmacies and money houses. In his father’s generation, Japanese pirates invaded, the situation was turbulent, and the people were displaced. So his father resolutely decided to open the shed to porridge and spread the medicine. After a few years of persistence, he finally dissipated his wealth, but they had no regrets. Where is the country broken?

In his generation, in response to the slogan of the great rejuvenation of the Chinese nation, he practiced his skills hard and looked forward to rebuilding the glory of the family one day...

Hey, follow up by yourself, let's implement four categories: his grandfather, his grandfather, his father, and him. String this story line together.

Come on! !

Insert picture description here
Insert picture description here
Insert picture description here

In the continuous update, you can follow up if you like it

Guess you like

Origin blog.csdn.net/qq_43762191/article/details/109067431