函数基础

'''
1. 组织结构混乱,可读性差
2. 代码冗余
3. 无法统一管理,维护难度极大
具备某一功能的工具即函数
函数的使用的必须遵循:先定义,后调用
'''

#函数分类:两大类

#1 内置函数:python解释器自带的函数,python解释器启动就会定义好这些函数
len()
max()
min()
sum()

#2 自定义函数:

#语法:
# def 函数名(参数1,参数2,...):
# """注释"""
# 函数体
# return 返回值

#定义阶段 可以不用参数和返回值,但必须要函数体
def tell_tag():
print('===========')

#调用阶段

tell_tag() #加()调用tell_tag函数

#函数就和定义一个变量是一个意思,也都要先定义再调用,特殊处就是函数的值可以加()调用
print(tell_msg) #输出的是内存地址,函数名=内存地址

#函数在定义阶段,只检测语法,不执行代码

#1.函数的使用必须遵循:先定义,后调用

#2.函数的定义,就相当于在定义一个变量,如果没有定义而直接调用,就相当于在引用一个不存在的变量名

#定义函数的三种形式
#无参 ()里面不填函数

#有参:函数体的代码,需要外部传入的值

#空函数 pass 可以搭建架构,然后一个一个实现

#1 调用函数:函数名(),
#需要注意:先通过名字找到函数的内存地址,然后加括号调用,执行里面的代码 做了两件事

#2 函数的返回值:return
#注意的第一点:
#在调用函数的过程中,一旦执行到return,就会立刻终止函数,并且把return后的结果当做本次调用的返回值返回
#函数体内可以有多个return,但是只能执行一次

#注意的第二点:
#返回的值,可以是任意类型 str,list等
#注意的第三点:
#没有return:默认返回None
#可以返回一个值===>值
#可以用逗号分隔,返回多个值===>tuple

#3:调用函数的三种形式:  1. 直接调用    2. 调用赋值 赋值是return的值    3. 函数运算赋值 运算的是return的值

#函数的参数

#形参与实参

#形参:在函数定义阶段,括号内定义的参数的称为形参,就相当于变量名
#实参:在函数调用阶段,括号内定义的参数的称为实参,就相当于变量值
#在调用阶段,实参的值会绑定给形参,在调用结束后,解除绑定
def foo(x,y): #形参 x=1,y=2
print(x,y)
foo(1,2) #实参

#参数的分类:

一:位置参数
位置形参:必须被传值的参数,多一个不行,少一个也不行
位置实参:从左到右依次赋值给形参
二:关键字参数:在函数调用阶段,按照key=value的形式定义实参
可以不依赖位置而指名道姓地给形参传值
需要注意的问题(可以与位置实参混用,但是):
1. 位置实参必须在关键字实参的前面
2. 不能为一个形参重传值

三:默认参数:在定义函数阶段已经为形参赋值了,在定义阶段已经赋值,意味着在调用阶段
可以不传值
注意的问题:
1 默认参数的值,只在定义时赋值一次
2 位置形参应该在默认参数的
3 默认参数的值应该是不可变类型

四:可变长参数 *args **kwargs
实参可变长度指的是:实参值的个数是不固定
而实参的定义形式无非两种:1、位置实参,2、关键字实参
针对这两种形式的实参个数不固定,相应的,形参也要有两种解决方案: *  **
#针对按照位置定义的溢出的那部门实参,形参:*args

#针对按照关键字定义的溢出的那部分实参,形参:**kwargs

#五:命名关键字参数(了解):
# 形参中,在*后定义的参数称之为命名关键字参数
# 它的特性是;传值时,必须按照关键字实参的形式传值

# 排序: 位置参数,默认参数,*args,命名关键字参数,**kwargs

函数的对象

#函数是第一类对象:函数可以当做数据来使用

#可以被引用

#可以当做参数传入一个#可以当做函数的返回值函数

#可以当做容器类型的一个元素

 1 #容器中的一个元素
 2 func_dic={
 3     'select':select,
 4     'update':update,
 5     'insert':insert,
 6     'delete':delete,
 7     'alter':alter
 8 }
 9 
10 def main():
11     while True:
12         inp=input('>>: ').strip()
13         if not inp:continue
14         sql=inp.split()
15         cmd=sql[0]
16 #        if cmd == 'select':
17 #            select(sql)
18 #        elif cmd == 'update':
19 #            update(sql)
20 #        elif cmd == 'insert':
21 #            insert(sql)
22 #        elif cmd == 'delete':
23 #            delete(sql)
24         if cmd in func_dic:        #简化优化
25             func_dic[cmd](sql)
26         else:
27             print('command not found')
28 
29 main()

#函数的嵌套

#1 函数的嵌套调用:在调用一个函数的过程中,又调用其他的函数

 1 #求两个值的最大值
 2 def my_max2(x,y):
 3 if x > y:
 4 return x
 5 else:
 6 return y
 7 
 8 #求四个值得最大值
 9 def my_max4(a,b,c,d):
10 res1=my_max2(a,b)
11 res2=my_max2(res1,c)
12 res3=my_max2(res2,d)
13 return res3
14 
15 res=my_max4(1,2,3,4)
16 print(res)

#2 函数的嵌套定义:在定义一个函数内部,又定义了一个函数

#注意调用层级

#名称空间和作用域

名称空间:存放名字与值绑定关系的地方

内置名称空间:

存放的是:内置的名字与值的绑定关系
生效:python解释器启动
失效:Python解释器关闭

全局名称空间

存放的是:文件级别定义的名字与值的绑定
生效:执行python文件时,将该文件级别定义的名字与值的绑定关系存放起来
失效:文件执行完毕

局部名称空间

存放的是:函数内部定义的名字与值的绑定关系
生效:调用函数时,临时生效
失效:函数调用结束

#python test.py
#1、python解释器先启动,因而首先加载的是:内置名称空间
#2、执行test.py文件,然后以文件为基础,加载全局名称空间
#3、在执行文件的过程中如果调用函数,则临时产生局部名称空间
加载顺序:先内置,再全局,最后局部
查找名字的顺序:先局部,再全局,最后内置

作用域:

全局作用域:包含内置名称空间的名字与全局名称空间的名字

  全局存活,全局有效

局部作用域:包含局部名称空间的名字

  临时存活,局部有效

#查看作用域:globals(),locals()
# LEGB 代表名字查找顺序: locals -> enclosing function -> globals -> __builtins__
# locals 是函数内的名字空间,包括局部变量和形参
# enclosing 外部嵌套函数的名字空间(闭包中常见) #f2()上有f1(),下有f3()
# globals 全局变量,函数定义所在模块的名字空间
# builtins 内置模块的名字空间

#global 全局   nonlocal 函数内部一层一层往上找,没有则报错

#注意:作用域关系,在函数定义时,就已经固定了,与调用位置无关

###模拟sql语句(时间不足,不够完善,没有insert的自增功能)###

  1 #coding:utf-8
  2 '''
  3 编写sql命令语句
  4 '''
  5 import os
  6 #定义数据库存放目录
  7 data_dir='C:/Users/lenovo/PycharmProjects/19期/day3/'
  8 #把sql切片,提取命令信息,分发给匹配函数执行, select * from db1.info where id>4 and id<20 limit 3
  9 def sql_parse(sql):
 10     '''
 11     把sql语句解析成可执行的语句
 12     :param sql:
 13     :return:
 14     '''
 15     sql_l=sql.split(' ')
 16     # print(sql_l)
 17     sql_dic={
 18         'select':select_parse,
 19         'insert':insert_parse,
 20         'update':update_parse,
 21         'delete':delete_parse,
 22     }
 23     func=sql_l[0]  #取列表的第一个字符串
 24     res=''
 25     if func in sql_dic:
 26         res=sql_dic[func](sql_l)   #执行匹配函数
 27     # print(res)
 28     return res
 29 
 30 def select_parse(sql_l):
 31     '''
 32     把sql定义可查询的语法结构,用handle_parse()解析
 33     :param sql_l:
 34     :return:
 35     '''
 36     sql_dic={
 37         'func':select,
 38         'select':[], #查询字段
 39         'from':[],   #数据.表
 40         'where':[],  #过滤条件
 41         'limit':[],  #limit条件
 42     }
 43     return handle_parse(sql_l,sql_dic)
 44 
 45 def insert_parse(sql_l):  #insert into db1.info values 39 王朝 24 17000106910 DBA 2017-09-18 18:39:56
 46     '''
 47     把sql定义可插入的语法结构,用handle_parse()解析
 48     :param sql_l:
 49     :return:
 50     '''
 51     sql_dic={
 52         'func':insert,
 53         'into':[],
 54         'values':[],
 55     }
 56     return handle_parse(sql_l,sql_dic)
 57 
 58 def update_parse(sql_l): #update db1.info set name='alex' where id=21 and name='王朝'
 59     '''
 60     把sql定义可更新的语法结构,用handle_parse()解析
 61     :param sql_l:
 62     :return:
 63     '''
 64     sql_dic={
 65         'func':update,
 66         'update':[],
 67         'set':[],
 68         'where':[]
 69     }
 70     return handle_parse(sql_l,sql_dic)
 71 
 72 def delete_parse(sql_l):  #delete from db1.info where id=3
 73     '''
 74     把sql定义可删除的语法结构,用handle_parse()解析
 75     :param sql_l:
 76     :return:
 77     '''
 78     sql_dic={
 79         'func':delete,
 80         'from':[],
 81         'where':[],
 82     }
 83     return handle_parse(sql_l,sql_dic)
 84 
 85 def handle_parse(sql_l,sql_dic):
 86     '''
 87     执行解析操作
 88     :param sql_l:
 89     :return:
 90     '''
 91     # print(sql_l,sql_dic)
 92     # print(sql_l.index('select'))
 93     for k in sql_dic:
 94         if k not in sql_l:continue
 95         start_index=int(sql_l.index(k)+1)
 96         for addindex in range(start_index,len(sql_l)):
 97             if sql_l[addindex] in sql_dic:break
 98             sql_dic[k].append(sql_l[addindex])
 99             # sql_dic['k']=sql_l[int(sql_l.index('k'))+1:int(sql_l.index('from'))]
100         # print(sql_dic[k])
101     # print(sql_dic)
102     return sql_dic
103 
104 #sql执行函数
105 def sql_action(sql_dic):
106     '''
107 
108     :return:
109     '''
110     sql_dic['func'](sql_dic)
111 
112 def select(sql_dic):
113     filter=''
114     limit_filter=''
115     count=0
116     l=sql_dic['from'][0].split('.')
117     # print(l)
118     rf=data_dir+'/'.join(l)
119     # wf=data_dir+l[0]+'/.swap.bak'
120     # print(rf)
121     if sql_dic['where']:
122         for i in sql_dic['where']:
123             filter = filter + i.replace('=', '==') + ' '
124         # print(filter)
125     if sql_dic['limit']:
126         limit_filter = int(sql_dic['limit'][0])
127     for i in sql_dic['select']:
128         sel_filter = i.split(',')
129     with open(rf, 'r', encoding='utf-8') as read_file:
130         for line in read_file:
131             l=line.split()
132             id=int(l[0])
133             name=l[1]
134             age=int(l[2])
135             phone=l[3]
136             job=l[4]
137             entry_date=l[5]
138             entry_time=l[6]
139             if filter:
140                 if eval(filter):
141                     if limit_filter:
142                         if count==limit_filter:break
143                     if sel_filter[0]=='*':
144                         print(line)
145                         count+=1
146                     else:
147                         for i in range(len(sel_filter)):
148                             print(eval(sel_filter[i]),end=' ')
149                         print()
150                         count+=1
151             else:
152                 if limit_filter:
153                     if count == limit_filter: break
154                 if sel_filter[0] == '*':
155                     print(line)
156                     count += 1
157                 else:
158                     for i in range(len(sel_filter)):
159                         print(eval(sel_filter[i]),end=' ')
160                     print()
161                     count += 1
162 
163 
164 
165 def insert(sql_dic):
166     filter=''
167     l=sql_dic['into'][0].split('.')
168     # print(l)
169     rf=data_dir+'/'.join(l)
170     add_line=' '.join(sql_dic['values'])+'
'
171     with open(rf, 'a', encoding='utf-8') as add_file:
172         add_file.write(add_line)
173 
174 def update(sql_dic):
175     filter=''
176     l=sql_dic['update'][0].split('.')
177     # print(l)
178     rf=data_dir+'/'.join(l)
179     wf=data_dir+l[0]+'/.swap.bak'
180     # print(wf)
181     # 'id=21' -->id == 21
182     # sql_dic['where']-->int(i[0])==21
183     # print(sql_dic['where'])
184     if sql_dic['where']:
185         for i in sql_dic['where']:
186             filter = filter + i.replace('=', '==') + ' '
187     # print(filter,type(eval(filter)))
188     for i in sql_dic['set']:
189         set_filter = i.split('=')
190     # print(set_filter,type(set_filter))
191     with open(rf, 'r', encoding='utf-8') as read_file,
192         open(wf,'w',encoding='utf-8') as write_file:
193         for line in read_file:
194             l=line.split()
195             id=int(l[0])
196             name=l[1]
197             age=int(l[2])
198             phone=l[3]
199             job=l[4]
200             entry_date=l[5]
201             entry_time=l[6]
202             if filter:
203                 if eval(filter):
204                     line=line.replace(eval(set_filter[0]),set_filter[1])
205                     # print(eval(set_filter[0]),set_filter[1])
206                     # print(line)
207                 write_file.write(line)
208             else:
209                 line = line.replace(eval(set_filter[0]), set_filter[1])
210                 write_file.write(line)
211     os.remove(rf)
212     os.rename(wf,rf)
213 
214 def delete(sql_dic):
215     filter=''
216     l=sql_dic['from'][0].split('.')
217     # print(l)
218     rf=data_dir+'/'.join(l)
219     wf=data_dir+l[0]+'/.swap.bak'
220     if sql_dic['where']:
221         for i in sql_dic['where']:
222             filter = filter + i.replace('=', '==') + ' '
223     with open(rf, 'r', encoding='utf-8') as read_file, 
224         open(wf, 'w', encoding='utf-8') as write_file:
225         for line in read_file:
226             l = line.split()
227             id = int(l[0])
228             name = l[1]
229             age = int(l[2])
230             phone = l[3]
231             job = l[4]
232             entry_date = l[5]
233             entry_time = l[6]
234             if filter:
235                 if eval(filter):continue
236                 write_file.write(line)
237             else:
238                 write_file.write()
239     os.remove(rf)
240     os.rename(wf, rf)
241 
242 
243 #主函数
244 if __name__=='__main__':
245     while True:
246         sql=input('sql>').strip()
247         if sql == 'exit':break
248         if not sql:continue
249         sql_dic=sql_parse(sql)
250         sql_action(sql_dic)
251         # select(sql_dic)
252         # update(sql_dic)
253         # delete(sql_dic)
本文是作者本人的笔记心得,如果有bug请评论留言; 如果本文对你有帮助,请点击【好文要顶】和【关注我】以示鼓励; 大家也可以关注我的微信订阅号【ysgxming】一起交流学习。
原文地址:https://www.cnblogs.com/DemonAngel/p/7581862.html