立即学习:https://edu.csdn.net/course/play/25504/304708?utm_source=blogtoedu
# python中函数即是变量
# abs(-10)函数调用,abs是函数本身
print(abs(-10))
# 函数同样可以赋值给变量
f=abs
print(f(-10))
# abs也可以被覆盖掉
# abs=10
# abs(-10)
# 函数可以作为参数传递
def add(x,y,f):
return f(x)+f(y)
print(add(-5,6,abs))
'''
map函数
'''
l = [1,2,3,4,5,6,7,8,9]
def f(x):
return x*x
m = map(f, l)
print(m) #结果以迭代器对象返回
# 迭代器只能访问一遍
# print(list(m))
# for n in m:
# print(n)
print(next(m))
print(next(m))
print(next(m))
# 将l列表中的每个int转换成字符串
l=[1,2,3,4,5,6,7,8,9]
print(list(map(str,l)))
'''
reduce
'''
l=[1,2,3,4,5,6,7]
from functools import reduce
def f(x,y):
return x*10+y
print(reduce(f, l))
# 实现str2int
def char2int(x):
digits = {'0':0, '1':1, '2':2, '3':3, '4':4, '5':5, '6':6, '7':7, '8':8, '9':9}
return digits[x]
print(reduce(f, map(char2int, '23556')))
'''
匿名函数,在函数中定义函数
'''
DIGITS = {'0':0, '1':1, '2':2, '3':3, '4':4, '5':5, '6':6, '7':7, '8':8, '9':9}
def str2int(s):
def f(x,y):
return x*10 +y
def char2int(x):
return DIGITS[x]
return reduce(f, map(char2int, s))
print(str2int('123556'))
# lambda表达式
def str2int(s):
def char2num(s):
return DIGITS[s]
return reduce(lambda x,y:x*10+y,map(char2num,s))
print(str2int('2432546567'))
'''
装饰器Decorator
'''
import datetime
# 装饰器 以一个函数作为参数,并返回一个函数
def log(f):
def write_log(*args,**kw):
with open('./a.txt','w') as f1:
f1.write(f.__name__)
print('写入日志成功,函数名字是:%s' % f.__name__)
return f(*args,**kw)
return write_log
def now():
print(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
now()
# 调用方式一
# ff = log(now)
# ff()
# print(ff.__name__)
# 调用方式二
@log
def now():
print(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
now()
'''
python内置的装饰器 @property @setter
'''
# 加上装饰器,方法变属性
class Student(object):
def __init__(self, score):
self.__score = score
def get_grade(self):
if self.__score >= 90:
return 'A'
elif self.__score >=60:
return 'B'
else:
return 'C'
@property # 在读函数前加上property,读函数变成属性访问
def score(self):
return self.__score
@score.setter # 在写函数前加上setter,写函数变成属性访问
def score(self, score):
if 0<=score<=100:
self.__score = score
else:
raise ValueError("不符合规范的输入")
stu1=Student(56)
print(stu1.score)
stu1.score = 78
print(stu1.score)
def normalize(name):
s1=name[0].upper()
s2=name[1:].lower()
return s1+s2
L1=['MIKE','asfdg','SADAGF']
L2=list(map(normalize,L1))
print(L2)