您的位置:首页 > 编程语言 > Python开发

【再回首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)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: