Python-函数

Python-函数


函数在Python中扮演着什么样的角色?
1.最大化的代码重用和最小的代码冗余
2.流程的分解

首先让我们编写一个最简单的函数'hello world!'

def helloWorld():
	print('hello world!')

怎么调用? ⤵️

helloWorld()

输出什么呢?

hello world!
[Finished in 0.0s] # 运行用时!!!

在此需要注意的是函数的调用要放在函数体的下面,否则⤵️

Traceback (most recent call last):
  File "/Users/caoxu/Desktop/Prthon_Automatic/2017-01-19/函数.py", line 8, in <module>
    helloWorld()
NameError: name 'helloWorld' is not defined
[Finished in 0.0s with exit code 1]
[shell_cmd: python -u "/Users/caoxu/Desktop/Prthon_Automatic/2017-01-19/函数.py"]
[dir: /Users/caoxu/Desktop/Prthon_Automatic/2017-01-19]
[path: /usr/bin:/bin:/usr/sbin:/sbin]

是的他会报错,由此可以知道的是如果我们事先实现了两个函数,当其中一个调用另一个时,被调用函数要在调用函数前实现.

到这里最简单的函数就实现完毕了,但是函数才刚刚开始.

def语句

def语句的作用是创建一个函数对象,并且将该对象赋值给我们定义的变量名(函数名),def语句格式一般如下⤵️(没有返回值的函数)

def <name><arg1,arg2,.....,argN>
	<statements>

(有返回值的函数)

def <name><arg1,arg2,.....,argN>
	......
	return <values>

def语句是实时执行的:说的通俗一点也就是没有想C等语言的编译,就像读文章一样,如果文章一共有1000行,你不读到1000行你就不会知道1000行写的是什么内容(为了证实这个现象下面是一个测试的小样例⤵️)

def helloWorld():
	print('hello world!')

helloWorld()

def newhelloWorld():
	print('new hello world!')
	helloWorld()

newhelloWorld()

现在上面的代码是完全正确的,运行它>>>

hello world!
new hello world!
hello world!
[Finished in 0.0s]

现在我要对它做一点点小改动(raw_input():在python中他是输入函数)

def helloWorld():
	raw_input('hello world!>>>')
	print('hello world!')

helloWorld()

def newhelloWorld():
	raw_input('new hello world!>>>')
	print('new hello world!')
	helloWorld()

newhelloWorld()

结果⤵️

hello world!>>> # 按回车即可
hello world!
new hello world!>>> # 按回车即可
new hello world!
hello world!>>> # 按回车即可
hello world!

事实上上面所展示的两种方式并不能很形象的展示出实时执行这一特点,但是我们多多少少可以去感受那么一点点感觉😁

return

读到这里如果你细心,我想应该已经看到了return的字样.那么我们就来看看return是什么!

def function():
	return 'hi'

function()

function中出现的return,但是当我调用他的时候并没有任何输出就像结果一样⤵️

[Finished in 0.0s]

那么我们稍微修改一下代码>>>

def function():
	return 'hi'

print(function())

我们把function放在print函数里面,然后结果是这样的⤵️

hi
[Finished in 0.0s]

它输出结果了(return的作用是把return后的值返回给调用者)

多态

是多态不是变态!!!

多态是面向对象语言的一个基本特性,多态意味着函数并不知道是被谁(调用对象)调用,根据调用对象的不同表现不同的行为方式。
在处理多态对象时,我们只需要关注它的接口即可(在使用对象的使用先假定有该接口,如果实际并不包含,在运行中报错。)
下面是多态的的表达形式,不过这里需要使用class的知识,在此不多介绍.

class dog(object):
	def __init__(self):
		pass
	def call(self):
		print('汪!')

class cat(object):
	def __init__(self):
		pass
	def call(self):
		print('喵!')

dog().call()
cat().call()

Log⤵️

汪!
喵!
[Finished in 0.0s]

如结果所示:相同的方法被不同的调用者调用,所打印的内容不同->这就叫做多态!

posted @ 2017-01-20 11:25  旭宝爱吃鱼  阅读(317)  评论(0编辑  收藏  举报