Python笔记(四):函数与函数式编程

编程方式分为:面向对象面向过程以及函数式编程

面向对象:类 –> class
面向过程:过程 –> def
函数式编程:函数 –> def



函数

函数的定义

面向过程和函数都是 def,那他们的区别是什么呢?

#函数
def text():
    '''testing'''         #文档描述
    print("in the func1")
    reture 0

#过程
def text2():
    '''testing2'''
    print("in the func2")

x = text()             #没有这两句是不会打印内容的
y = text2()                   (调用)

>> in the func1
>> in the func2

print("from func1 return is %s"%x)
print("from func2 return is %s"%y)

>> from func1 return is 0
>> from func2 return is None

过程就是没有返回值的函数
当函数/过程没有使用 return 显示的定义返回值时,Python 解释器会隐式的返回None,所以在 Python 中,过程也可以算作函数。

函数的优点

生成日志:

import time

def logger():
    time_format = "%Y-%m-%d %X"       #年月日时间的格式
    time_current = time.strftime(time_format)

    with open("a.txt","a+") as f:
        f.write("%s end action\n" %time_current)

def test1():
    print("in the test1")
    logger()

def test2():
    print("in the test2")
    logger()

def test3():
    print("in the test3")
    logger()

test1()           #运行该函数
test2()
test3()

>> in the test1       #输出结果打印这三项
>> in the test2
>> in the test3

新生成的 a.txt :
2018-05-19 09:17:11 end action
2018-05-19 09:17:11 end action
2018-05-19 09:17:11 end action

定义的函数只要修改logger函数,其余的均一起修改,所以函数具有:
- 代码重用
- 保持一致性
- 可扩展性

函数的返回值

定义三个函数,返回值分别为:
- 不写 return
- return 0
- return 数字、字符串、列表和字典

def test1():
    print("in the test1")

def test2():
    print("in the test2")
    return 0

def test3():
    print("in the test3")
    return 1,"Evan",["a","b"],{"list":"coffee"}

x = test1()           #运行该函数
y = test2()
z = test3()

print(x)
print(y)
print(z)

>> in the test1
>> in the test2
>> in the test3
>> None
>> 0
>> (1, 'Evan', ['a', 'b'], {'list': 'coffee'})

可以看到,当return 一系列的东西时,其返回值会放在一个元组里。
return也可以返回另一个函数,但返回值是另一个函数的地址

有参函数的实参与形参

def test(x,y):
    print(x)
    print(y)

def test(x,y=2)
    print(x)
    print(y)

#默认参数:调用函数时,默认函数非必须传递
1、(用于软件默认安装等位置)选装时有必装选项;
2、数据库默认端口号


#实参数量不固定的情况,定义形参:
def test(*a):                  #以*开头,可接受多个实参放入元组中
    print(a)

test(1,2,3,4,5,6)           #   a = tuple[1,2,3,4,5,6]

···················

def test(x,*a):
    print(x)
    print(a)
test(1,2,3,4,5,6)

>> 1
>> (2,3,4,5,6)

接收字典

def test(**kwargs):
    print(kwargs)
    print(kwargs["name"])

test(name = "Evan",age = 22,sex = "M")
test(**{"name":"Evan","age":22,"sex":"M"})  #两句效果一样

>> {'name': 'Evan', 'age': 22, 'sex': 'M'}
>> Evan
# **kwargs: 把N个关键字参数转换成字典的方式

·················
def test(name,age = 22,*args,**kwargs):
    print(name)
    print(age)
    print(args)
    print(kwargs)
test("Evan",age = 99,sex = "M",hobby = "Car")

>> Evan
>> 99
>> ()                     #空元组
>> {'sex': 'M', 'hobby': 'Car'}

函数式编程

函数式编程与函数不是一回事!
可归结到面向过程的程序设计,但思想更接近数学计算
此处的函数指的是数学里的函数(数学意义上的计算)

重要特点:只要输入是确定的,输出就是确定的。

[(1+2)*3]/4

#面向过程
var a = 1+2;
var b = a*3;
var c = b/4;

#函数式编程
var result = subtract(multiply(add(1,2),3),4);

猜你喜欢

转载自blog.csdn.net/weixin_42026630/article/details/80374078