【再回首Python之美】【函数】自定义函数
2018-02-07 14:59
351 查看
自定义函数:
使用自定义函数可以提高公共功能代码的使用率,减少工程代码总体代码量。
当出现问题时,可以做到修改一个函数而一劳永逸。
示例代码:
#ex_function.py
self_file = __file__ #save current file absolute path
print "\ndefine myself function without param"
def hello_without_param():
print "hello world"
hello_without_param() #hello world.
print "\ndefine myself function with param"
def hello_with_param(somebody):
print "hello %s" % somebody
hello_with_param("Tom") #hello Tom.
print "\ndefine myself function with default param"
def hello_with_defaultparam(somebody = "Lucy"):
print "hello %s" % somebody
hello_with_defaultparam() #hello Lucy
hello_with_defaultparam("Kitty") #hello Kitty
print "\ndefine myself function with many default param"
#部分入参提供默认参数时,这些参数必须在参数列表最后
def hello_withmany_defaultparam(op, somebody = "Lucy"):
print "%s %s" % (op, somebody)
hello_withmany_defaultparam("hello") #hello Lucy
hello_withmany_defaultparam("hello", "Kitty") #hello Kitty
hello_withmany_defaultparam("Like", "Kitty") #Like Kitty
print "\n exit %s" % self_file
编译执行:
(end)
使用自定义函数可以提高公共功能代码的使用率,减少工程代码总体代码量。
当出现问题时,可以做到修改一个函数而一劳永逸。
示例代码:
#ex_function.py
self_file = __file__ #save current file absolute path
print "\ndefine myself function without param"
def hello_without_param():
print "hello world"
hello_without_param() #hello world.
print "\ndefine myself function with param"
def hello_with_param(somebody):
print "hello %s" % somebody
hello_with_param("Tom") #hello Tom.
print "\ndefine myself function with default param"
def hello_with_defaultparam(somebody = "Lucy"):
print "hello %s" % somebody
hello_with_defaultparam() #hello Lucy
hello_with_defaultparam("Kitty") #hello Kitty
print "\ndefine myself function with many default param"
#部分入参提供默认参数时,这些参数必须在参数列表最后
def hello_withmany_defaultparam(op, somebody = "Lucy"):
print "%s %s" % (op, somebody)
hello_withmany_defaultparam("hello") #hello Lucy
hello_withmany_defaultparam("hello", "Kitty") #hello Kitty
hello_withmany_defaultparam("Like", "Kitty") #Like Kitty
print "\n exit %s" % self_file
编译执行:
(end)
相关文章推荐
- Python 实现类似PHP的strip_tags函数功能,并且可以自定义设置保留标签(一)
- python自定义排序函数
- python自定义函数大全
- python 如何能否自定义模块路径? 添加自定义模块 函数 python
- 洗礼灵魂,修炼python(25)--自定义函数(6)—从匿名函数进阶话题讲解中解析“函数式编程”
- python基础之函数(自定义函数)
- python中map、reduce、filter、自定义排序函数、装饰器函数和偏函数
- python中的如何导入自定义函数
- Python自定义函数基础:获取函数单返回值和多返回值
- python class根据配置自定义函数
- Python写的创建文件夹自定义函数mkdir()
- Python自定义函数的5种常见形式
- Python 实现类似PHP的strip_tags函数功能,并且可以自定义设置保留标签
- python自定义函数返回值调用
- Python3.x自定义比较函数
- python中自定义排序函数
- python自定义日志函数测试
- Python-Pandas(4)自定义函数方法
- 第7课 Python自定义函数基础:有形参和实参解析
- python:自定义函数、hashlib(md5、sha1)、base64