學習筆記(10):第二章 程序設計與數據結構-看Python如何靈活應用經典設計模式 4...

立即學習: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)

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章