7.函数
7.1 定义函数
例1:
#定义函数:举例定义输出10以内奇数的函数
def Odd_number_within_10():
number1 = 0
while number1 < 10:
number1 += 1
if number1 % 2 == 0:
continue
print number1
Odd_number_within_10()
输出为:
1
3
5
7
9
例2:
#向函数传递信息:当a=15时,输出a以内的奇数
def Odd_number(a):
number1 = 0
while number1 < a:
number1 += 1
if number1 % 2 == 0:
continue
print number1
Odd_number(15)
输出为:
1
3
5
7
9
11
13
15
在这个例子中a为形参,15为实参。
7.2 传递实参
例如下面这个函数:
# 举例:输出a-b之间的奇数
def Odd_number(a,b):
number1 = 0
while number1 < a:
number1 += 1
while a <= number1 < b:
number1 += 1
if number1 % 2 == 0:
continue
print number1
(1)位置实参:实参的位置和形参的位置一一对应,在本例子中a与2对应b与8对应
Odd_number(2,8)
输出为:
3
5
7
多次调用函数:
Odd_number(2,8)
print ("\n")
Odd_number(4,10)
输出为:
3
5
7
5
7
9
(2)关键字实参:无需考虑实参顺序,而且还清楚的指出函数调用中各个值的用途
Odd_number(a=4,b=10)
输出为:
5
7
9
(3)默认值实参
def Odd_number(a,b=12): #给形参指定默认值时等会两边不能有空格,调用时也如此
number1 = 0
while number1 < a:
number1 += 1
while a <= number1 < b:
number1 += 1
if number1 % 2 == 0:
continue
print number1
Odd_number(1)
输出为:
3
5
7
9
11
7.3 返回值
例1:
#1.返回简单值
def name(first_name,last_name):
full_name = first_name + ' ' + last_name
return full_name.title()
#调用返回值函数时,需要提供一个变量用于存储返回的值。
a1 = name('gao','chi')
print a1
输出为:
Gao chi
例2:
#2.让实参变成可选的
#当有的实参不一定存在时可以将该形参变成下列可选的形式,这样运行时不会出错
def name1(first_name,last_name,middle_name=''):
full_name1 = first_name + ' ' + middle_name + ' ' + last_name
return full_name1.title()
b1 = name1('gao','chi')
print b1
b2 = name1('Franklin','Roosevelt','Delano')
print b2
输出为:
Gao Chi
Franklin Delano Roosevelt
例3:
#3.返回字典
def name2(first_name,last_name):
person = {'first':first_name ,'last': last_name}
return person
c1 = name2('gao','chi')
print c1
输出为:
{'last': 'chi', 'first': 'gao'}
例4:
#4.结合使用函数和while循环
def name3(first_name,last_name):
full_name = first_name + ' ' + last_name
return full_name.title()
while True:
print "Please tell me your name:"
print "enter 'q' to quit"
f_name = raw_input("First name: ")
if f_name == 'q':
break
l_name = raw_input("Last name: ")
if l_name == 'q':
break
name03 = name3(f_name,l_name)
print "Hello, " + name03 + "!"
输入:
Please tell me your name:
enter 'q' to quit
First name: gao
Last name: chi
Please tell me your name:
enter 'q' to quit
First name: q
输出为:
Hello, Gao Chi!
7.4 传递列表
例如:
#传递列表:例如打印后移到另一个列表
#打印模型函数:
def print_models(unprinted_gc,printed_gc):
while unprinted_gc:
current_gc = unprinted_gc.pop() #将未打印列表送进列表循环
print "printing gc:" + current_gc
printed_gc.append(current_gc) #将打印后的内容送进已打印列表
#显示模型函数:
def show(printed_gc):
print "printed gc:"
for printed_gc0 in printed_gc: #显示已打印的内容
print (printed_gc0)
(1)在函数中修改列表
#1.在函数中修改列表
unprinted_gc0 = ['a','b','c']
printed_gc0 = []
print_models(unprinted_gc0,printed_gc0)
show(printed_gc0)
print unprinted_gc0 #查看未打印列表是否改变
输出为:
printing gc:c
printing gc:b
printing gc:a
printed gc:
c
b
a
[]
(2)使用切片表示法禁止函数修改列表同时还不影响程序运行
#2.禁止函数修改列表
unprinted_gc1 = ['a','b','c']
printed_gc1 = []
#切片表示法[:]可以创建列表的副本,在函数中改变的是副本,即原列表不会在函数中被改变
print_models(unprinted_gc1[:],printed_gc1)
show(printed_gc1)
print unprinted_gc1
输出为:
printing gc:c
printing gc:b
printing gc:a
printed gc:
c
b
a
['a', 'b', 'c']
7.5 传递任何数量的实参
例1:
#1.结合使用位置实参和任意数量的实参
def gc(number,*names): #当不知有多少个实参时可以在形参前面加*,这样可以让python创建一个名字为names的空元组
print "number:" + str(number) + " name:"
for topping in names:
print topping
gc(1,'a')
gc(3,'a','b','c')
输出为:
number:1 name:
a
number:3 name:
a
b
c
例2:
#2.使用任意数量的关键字实参
def gc(first,last,**middle): #当不知有多少个实参时可以在形参前面加**,这样可以让python创建一个名字为names的空字典
name = {}
name['first name'] = first
name['last name'] = last
for key,value in middle.items():
name[key] = value
return name
full_name = gc('zhu ge','liang',zi='kong ming',hao='wo long')
print full_name
输出为:
{'last name': 'liang', 'first name': 'zhu ge', 'zi': 'kong ming', 'hao': 'wo long'}
7.6 将函数存储在模块中
本节要导入的模块为mokuai,具体代码为:
#coding:gbk
#输出a-b之间的奇数
def Odd_number(a,b):
number1 = 0
while number1 < a:
number1 += 1
while a <= number1 < b:
number1 += 1
if number1 % 2 == 0:
continue
print number1
#姓名函数
def name1(first_name,last_name,middle_name=''):
full_name1 = first_name + ' ' + middle_name + ' ' + last_name
return full_name1.title()
#打印模型函数:
def print_models(unprinted_gc,printed_gc):
while unprinted_gc:
current_gc = unprinted_gc.pop() #将未打印列表送进列表循环
print "printing gc:" + current_gc
printed_gc.append(current_gc) #将打印后的内容送进已打印列表
例1:
#1.导入整个模块
import mokuai
mokuai.Odd_number(2,8)
a = mokuai.name1('gao','chi')
print a
输出为:
3
5
7
Gao Chi
例2:
#2.导入特定函数
#导入语法为:from 模块名 import 函数名
#多个函数则为:from 模块名 import 函数名1,函数名2
from mokuai import Odd_number,print_models
Odd_number(2,8)
unprinted_gc0 = ['a','b','c']
printed_gc0 = []
print_models(unprinted_gc0,printed_gc0)
输出为:
3
5
7
printing gc:c
printing gc:b
printing gc:a
例3:
#3.使用as给函数指定别名:from 模块名 import 函数名 as 函数别名
from mokuai import Odd_number as on
on(2,8)
例4:
#4.使用as给模块指定别名:import 模块名 as 模块别名
import mokuai as mk
mk.Odd_number(2,8)
例5:
#5.导入模块中的所有函数:使用*即可导入所有函数
from mokuai import *
Odd_number(2,8)
a = name1('gao','chi')
print a
unprinted_gc0 = ['a','b','c']
printed_gc0 = []
print_models(unprinted_gc0,printed_gc0)
输出为:
3
5
7
Gao Chi
printing gc:c
printing gc:b
printing gc:a
8.类
8.1 创建和使用类
例1:
#1.创建类
class Dog(object): #创建小狗类
def __init__(self,name,age): #初始化属性name和age
self.name = name
self.age = age
def sit(self):
print self.name.title() + "is now sitting." #模拟小狗被命令的时候蹲下
def roll_over(self):
print self.name.title() + "rolled over !" #模拟小狗被命令的时候打滚
注释:我们将类中的函数叫做方法,方法__init__()作用是初始化已实例化后的对象;子类可以不重写__init__,实例化子类时,会自动调用父类中已定义的__init__。
例2:
#2.根据类创建实例
my_dog = Dog('willie',6)
print "dog name:" + my_dog.name.title() #访问dog类中的属性
print "dog age:" + str(my_dog.age)
print ("\n")
my_dog.sit() #调用类中的方法
my_dog.roll_over()
print ("\n")
输出为:
Willie is now sitting.
Willie rolled over !
例3:
my_dog = Dog('willie',6)
your_dog = Dog('lucy',3)
print "my dog name:" + my_dog.name.title() + " my dog age:" + str(my_dog.age)
print "your dog name:" + your_dog.name.title() + " your dog age:" + str(your_dog.age)
my_dog.sit()
your_dog.roll_over()
输出为:
my dog name:Willie my dog age:6
your dog name:Lucy your dog age:3
Willie is now sitting.
Lucy rolled over !
8.2 使用类和实例
例1:
#1.给属性加默认值
class Car0(object):
def __init__(self,make,model,year): #初始化属性
self.make = make
self.model = model
self.year = year
self.odometer_reading = 0 #添加一个新属性里程,并且初始值为0
def get_describe_name(self): #添加描述方法
long_name = str(self.year) + ' ' + self.make + ' ' + self.model
return long_name.title()
def read_odometer(self):
print "mileage:" + str(self.odometer_reading)
my_new_car = Car0('aodi','a4','2021')
print my_new_car.get_describe_name()
my_new_car.read_odometer()
#2.修改属性值
my_new_car.odometer_reading = 12 #(1) 方法1,直接修改属性的值
my_new_car.read_odometer()
输出为:
2021 Aodi A4
mileage:0
mileage:12
例2:
#(2)方法2:通过方法修改属性值
class Car1(object):
def __init__(self,make,model,year): #初始化属性
self.make = make
self.model = model
self.year = year
self.odometer_reading = 0 #添加一个新属性里程,并且初始值为0
def get_describe_name(self): #添加描述方法
long_name = str(self.year) + ' ' + self.make + ' ' + self.model
return long_name.title()
def read_odometer(self): #显示里程
print "mileage:" + str(self.odometer_reading)
def update_odometer(self,mileage): #添加修改指定里程的方法
self.odometer_reading = mileage
def increament_odometer(self,miles): #添加里程增加指定的值的方法
self.odometer_reading += miles
my_new_car = Car1('aodi','a4','2021')
print my_new_car.get_describe_name()
my_new_car.update_odometer(23500)
my_new_car.read_odometer()
my_new_car.increament_odometer(300)
my_new_car.read_odometer()
输出为:
2021 Aodi A4
mileage:23500
mileage:23800
8.3 继承
例如:
#继承(子类与父类)
class Car(object):
def __init__(self,make,model,year): #初始化属性
self.make = make
self.model = model
self.year = year
self.odometer_reading = 0 #添加一个新属性里程,并且初始值为0
def get_describe_name(self): #添加描述方法
long_name = str(self.year) + ' ' + self.make + ' ' + self.model
return long_name.title()
def read_odometer(self):
print "mileage:" + str(self.odometer_reading)
def update_odometer(self,mileage): #添加修改指定里程的方法
if mileage >= self.odometer_reading:
self.odometer_reading = mileage
else:
print "you can't roll back an odometer"
self.odometer_reading = mileage
def increament_odometer(self,miles): #添加里程增加指定的值的方法
self.odometer_reading += miles
class battery():
def __init__(self,battery_capacity=70): #将很多针对电动车的battery的属性可以单独提取出来形成一个battery类
self.battery_capacity = battery_capacity
def get_range(self): #新增的和battery容量相关的得到续航里程的方法
if self.battery_capacity == 70:
range = 240
elif self.battery_capacity ==85:
range = 270
message = "range:" + str(range)
print message
def describe_battery(self):
print "battery capacity:" + str(self.battery_capacity) + "KWh"
class ElecticCar1(Car): #添加子类电动汽车
def __init__(self,make,model,year): #初始化父类属性
# 使用super函数让子类实例包含父类的所有属性,所以父类也叫超类,另外在python3中使用的方式是super.__init__()
super(ElecticCar1, self).__init__(make,model,year)
self.battery = battery()
self.maximum_speed = 80 #增添子类的属性并设置初始值
def describe_maximum_speed(self): #添加子类的方法
print "maximum_speed:" + str(self.maximum_speed) + "Km/h"
my_tesla = ElecticCar1('tesla','model s','2021')
print my_tesla.get_describe_name()
my_tesla.describe_maximum_speed()
my_tesla.battery.describe_battery()
my_tesla.battery.get_range()
输出为:
2021 Tesla Model S
maximum_speed:80Km/h
battery capacity:70KWh
range:240
8.4 导入类
已知模块为car模块,代码如下所示:
#coding:gbk
class Car(object):
def __init__(self,make,model,year): #初始化属性
self.make = make
self.model = model
self.year = year
self.odometer_reading = 0 #添加一个新属性里程,并且初始值为0
def get_describe_name(self): #添加描述方法
long_name = str(self.year) + ' ' + self.make + ' ' + self.model
return long_name.title()
def read_odometer(self):
print "mileage:" + str(self.odometer_reading)
def update_odometer(self,mileage): #添加修改指定里程的方法
if mileage >= self.odometer_reading:
self.odometer_reading = mileage
else:
print "you can't roll back an odometer"
self.odometer_reading = mileage
def increament_odometer(self,miles): #添加里程增加指定的值的方法
self.odometer_reading += miles
class battery():
def __init__(self,battery_capacity=70): #将很多针对电动车的battery的属性可以单独提取出来形成一个battery类
self.battery_capacity = battery_capacity
def get_range(self): #新增的和battery容量相关的得到续航里程的方法
if self.battery_capacity == 70:
range = 240
elif self.battery_capacity ==85:
range = 270
message = "range:" + str(range)
print message
def describe_battery(self):
print "battery capacity:" + str(self.battery_capacity) + "KWh"
class ElecticCar1(Car): #添加子类电动汽车
def __init__(self,make,model,year): #初始化父类属性
# 使用super函数让子类实例包含父类的所有属性,所以父类也叫超类,另外在python3中使用的方式是super.__init__()
super(ElecticCar1, self).__init__(make,model,year)
self.battery = battery()
self.maximum_speed = 80 #增添子类的属性并设置初始值
def describe_maximum_speed(self): #添加子类的方法
print "maximum_speed:" + str(self.maximum_speed) + "Km/h"
例1导入单个类:
#1.导入单个类
from car import Car
my_new_car = Car('aodi','a4','2020')
print my_new_car.get_describe_name()
my_new_car.odometer_reading = 23
my_new_car.read_odometer()
输出为:
2020 Aodi A4
mileage:23
例2从一个模块导入多个类:
#2.从一个模块导入多个类
from car import Car,ElecticCar1
my_beetle = Car('gc','a1','2022')
print my_beetle.get_describe_name()
my_tesla = ElecticCar1('tesla','roadster','2022')
print my_tesla.get_describe_name()
输出为:
2022 Gc A1
2022 Tesla Roadster
例3.导入整个模块:
import car
my_beetle = car.Car('gc','a1','2022') #使用模块.类()的语法访问需要的类
print my_beetle.get_describe_name()
my_tesla = car.ElecticCar1('tesla','roadster','2022')
print my_tesla.get_describe_name()
例4导入模块中的所有类(不推荐这种导入方式):
from car import *
my_beetle = Car('gc','a1','2022')
print my_beetle.get_describe_name()
my_tesla = ElecticCar1('tesla','roadster','2022')
print my_tesla.get_describe_name()