Python入门:参数传递方式

来源:互联网 发布:杭州四季青淘宝货源 编辑:程序博客网 时间:2024/05/29 17:04

这是关于Python的第5篇文章,主要介绍下参数传递方式和如何设计自己的函数。

(一)

本篇主要介绍2种参数传递方式。

位置参数

调用函数时,根据函数定义的参数位置来传递参数。

def right_triangle_area(a,b):    return 1/2*a*bprint(right_triangle_area(3,4))# 位置参数传递

求直角三角形面积,a、b分别为两条直角边,这里调用函数时使用的是位置参数传递。在位置参数传递中,参数的顺序是不可改变的。

关键词参数传递

在调用函数时,通过“键=值”的形式加以指定。可以让函数更加清晰、容易使用,无需考虑参数顺序。

def right_triangle_area(a,b):    return 1/2*a*bprint(right_triangle_area(b=4,a=3))# 关键词参数传递

还有一些类型是默认参数和可变参数等,目前我暂时用不到,就不做详细分享,有兴趣的可以自行百度。

(二)

设计自己的函数

之前介绍了字符串的方法和如何创建函数,这里将前面的学到的内容整合起来,设计一个简易的敏感词过滤器。

1. 传入参数name(文件名)和msg(信息内容)就可以在桌面写入文件名称和内容的函数text_create,如果桌面没有这个可以写入的文件时,会创建一个再写入。

def text_create(name,msg):    # 创建文件,写入信息    desktop_path = '/Users/duwangdan/Desktop/'    # 桌面路径    full_path = desktop_path + name + '.txt'    # 桌面路径+文件名+文件后缀    file = open(full_path,'w')    # 'w'参数指写入    file.write(msg)    # 文件中写入信息    file.close()    # 写入后关闭文件
在上一篇《产品经理学Python:学会创建并调用函数》中提到,定义函数后需要return返回结果。在Python中,return是可选项,没有return也可以直接定义函数并顺利调用,当不写时,代表返回值是‘None’。

这时敏感词过滤器的第一部分已完成。

2. 定义一个名为text_filter的函数,传入参数word,cencored_word(敏感词)和changed_word(替换词),cencored_word默认给定‘Awesome’,用changed_word默认空值来替代,实现敏感词过滤。

def text_filter(word,censored_word='Awesome',change_word=''):    # 文本过滤函数    return word.replace(censored_word,change_word)    # 用replace()方法替换敏感词
3. 定义一个名为censored_text_create的函数,传入参数name(文件名),msg(信息),使用第2个函数text_filter,将传入的msg过滤后储存在clean_msg中,再将传入的name和过滤好的clean_msg作为参数传入text_create函数中,调用censored_text_create函数,可以得到过滤后的文本。
def censored_text_create(name,msg):    # 创建删除敏感词后的文本函数    clean_msg = text_filter(msg)    # 过滤掉msg中的敏感词    text_create(name,clean_msg)    # 传入name和clean_msg到text_create函数中censored_text_create('test','Math is Awesome!')# 调用函数
完成以上三步后,我们可以得到自己设计的文本过滤器了。

完整代码如下:

def text_create(name,msg):    desktop_path = '/Users/duwangdan/Desktop/'    full_path = desktop_path + name + '.txt'    file = open(full_path,'w')    file.write(msg)    file.close()def text_filter(word,censored_word='Awesome',change_word=''):    return word.replace(censored_word,change_word)def censored_text_create(name,msg):    clean_msg = text_filter(msg)    text_create(name,clean_msg)censored_text_create('test','Math is Awesome!')

操作环境:Python版本,3.6;PyCharm版本,2016.2;电脑:Mac

-----   End   -----

作者:杜王丹,微信公众号:杜王丹,互联网产品经理。


0 0