函数
def greet_user():
print(“hello”)
greet_user()
向函数传递信息
def greet_user(username):
print(“hello, “+username.title()+”!”)
greet_user(‘jesse’)
变量username是一个形参,值’jesse’是一个实参。实参是调用函数时传递给函数的信息。
向函数传递实参的方式很多,可使用位置实参,要求实参的顺序与形参的顺序相同;也可以使用关键字实参,每个实参由变量名和值组成;还可以使用列表和字典。
位置实参:
def describe_pet(animal_type,pet_name):
print(“\nI have a “+animal_tyle+”.”)
print(“My “+animal_type+”’s name is “+pet_name.title()+”.”)
describe(‘hamster’,’harry’)
关键字实参:
describe(animal_type=’hamster’,pet_name=’harry’)
默认值:
编写函数时,可以给每个形参指定默认值。在调用函数中给形参提供了实参,将使用指定的实参值,如果没有,则使用形参的默认值。
将形参设置有默认值,python将实参视为位置实参,如果函数调用中只包含宠物名字,这个实参将关联到函数定义中的第一个形参,因此修改了形参的位置。
def describe_pet(pet_name, animal_type=’dog’):
print(“\nI have a “+animal_tyle+”.”)
print(“My “+animal_type+”’s name is “+pet_name.title()+”.”)
describe_pet(pet_name=’whillie’)
describe_pet(pet_name=’harry’,animal_type=’hamster’)
返回值:
返回简单值
def get_formatted_name(first_name,last_name):
full_name=first_name+’ ‘+last_name
return full_name.title()
musician=get_formatted_name(‘jimi’,’hendrix’)
print(musician)
让实参变成可选的
def get_formatted_name(first_name,last_name,middle_name=’’):
if middle_name:
full_name=first_name+’ ‘+middle_name+’ ‘+last_name
else:
full_name=first_name+’ ‘+last_name
return full_name.title()
muscian=get_formatted_name(‘jimi’,’hendrix’)
muscian=get_formatted_name(‘john’,’hooker’,’lee’)
返回字典
def build_person(first_name,last_name):
person={‘first’:first_name,’last’:last_name}
return person
muscian=build_person(‘jimi’,’hendrix’)
print(muscian)
{‘first’:’jimi’,’last’:’hendrix’}
结合使用函数和循环while
while True:
print(“\nPlease tell me your name:”)
f_name=input(“First name:”)
l_name=input(“Last name:”)
formatted_name=get_formatted_name(f_name,l_name)
print(“\nHello,”+formatted_name+”!”)
传递列表
def greet_users(names):
for name in names:
msg=”Hello,”+name.title()+”!”
print(msg)
usernames=[‘hannah’,’try’,’margot’]
greet_users(usernames)
禁止函数修改列表
function_name(list_name[:])
传递任意数量的实参
def make_pizza(*toppings):
print(toppings)
make_pizza(‘pepperoni’)
make_pizza(‘mushrooms’,’green peppers’)
形参toppings中的让python创建一个名为toppings的空元组,并且将收到的所有值都封装到这个元组。
def make_pizza(*toppings):
for topping in toppings:
print(“-“+topping)
结合使用位置实参和任意数量实参
def make_pizza(size,**toppings):
print(“\n Making a “+str(size)+”-inch pizza with the following toppings:”)
for topping in toppings:
print(“-“+topping)
make_pizza(16,’pepperoni’)
使用任意数量关键字实参
有时需要接受任意数量的实参,但不知道传递给函数的是什么信息,可以将函数编写为可以接受任意数量的键值对**。
def build_profile(first,last,**user_info):
profile={}
profile[‘first_name’]=first
profile[‘last_name’]=last
for key,value in user_info.items():
profile[key]=value
return profile
user_profile=build_profile(‘abert’,’einstein’,location=’princeton’,field=’physics’)
将函数存储在模块中
导入整个模块
pizza.py
…
在pizza.py所在目录中创建另一个py文件
import pizza
pizza.make_pizza(16,’pepperoni’)
导入特定的模块
from pizza import make_pizza
使用as给函数指定别名
from pizza import make_pizza as mp
mp(16,’pepperoni’)
使用as给模块指定别名
import pizza as p
p.make_pizza(16,’pepperoni’)
导入模块中所有函数
from pizza import *
make_pizza(16,’pepperoni’)
类
根据类创建对象,每个对象都具备类中的通用行为,创建对象称为实例化。
class Dog():
def __init__(self,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()方法在创建实例时,Python会自动运行它,其中self形参必不可少,放到其他形参前边。
在创建dog实例时,自动传入实参self,每个与类关联的方法调用都会自动传递给实参self,它是一个指向实例本身的引用,让实例能够访问类中的属性和方法。
根据类创建实例
my_dog=Dog(‘whille’,6)
print(“My dog’s name is “+my_dog.name.title()+”.”)
print(“My dog is “+str(my_dog.age)+” years old.”)
调用方法
my_dog.sit()
my_dog.roll_over()
创建多个实例
my_dog=Dog(‘whille’,6)
your_dog=Dog(‘lucy’,3)
给属性指定默认值
类的每个属性必须有初始值。
class Car():
def __init__(self,make,model,year):
self.make=make
self.model=model
self.year=year
self.odometer_reading=0
def descriptive_name(self):
…
def read_odometer(self):
print(“This car has “+str(self.odometer_reading)+” miles on it.”)
my_new_car=Car(‘audi’,’a4’,2016)
my_new_car.read_odometer()
修改属性的值
my_new_car=Car(‘audi’,’a4’,2016)
my_new_car.odometer_reading=23
通过方法修改属性的值
class Car():
…
def update_odometer(self,mileage):
self.odometer_reading=mileage
my_new_car.update_odometer(23)
通过方法对属性的值进行递增
class Car:
…
def increment_odometer(self,miles):
self.odometer_reading+=miles
my_used_car=Car(‘subaru’,’outback’2013’)
my_used_car.update_odometer(23400)
my_used_car.increment_odometer(100)
继承
一个类继承另一个类,将自动获得另一个类的所有属性和方法,原有的类为父类,新类为子类。
创建子类的实例时,首先要完成的是给父类的所有属性赋值。
electric_car.py
class Car():
def __init__(self,make,model,year):
self.make=make
self.model=model
self.year=year
self.odometer_reading=0
…
class ElectricCar(Car): #定义子类时需要在括号内指定父类的名称
def __init__(self,make,model,year):
super().__init__(make,model,year) #super()将父类和子类关联起来,让ElectricCar的实例包含父类的所有属性
my_tesla=ElectricCar(‘tesla’,’model s’,2020)
print(my_tesla.get_descriptive_name())
给子类定义属性和方法
class ElectricCar(Car):
def __init__(self,make,model,year):
super().__init__(make,model,year)
self.battery_size=70
def descriptive_battery(self):
print(“This car has a “+str(self.battery_size)+”-kwh battery”)
my_tesla=ElectricCar(‘tesla’,’model s’,2020)
my_tesla.descriptive_battery()
对于父类的方法,如果不符合子类的行为,需要对其重写,在子类定义同样名称的方法。
class Car():
def fill_gas_tank(self):
…
class ElectricCar(Car):
…
def fill_gas_tank(self):
print(“This car doesn’t need a gas tank.”)
将实例用作属性
将Battery实例用作ElectricCar类的一个属性
class Car():
…
class Battery():
def ___init__(self,battery_size=70):
self.battery_size=battery_size
def describe_battery(self):
print(“This car has a “+str(self.battery_size)+”-kwh battery.”)
class ElectricCar(Car):
def __init__(self,make,model,year):
super().__init__(make,model,year)
self.battery=Battery()
…
my_tesla.battery.describe_battery()
导入单个类
car.py
…
my_car.py
from car import Car
my_new_car=Car(‘audi’,’a4’,2020)
在一个模块中存储多个类
car.py
class Car():…
class ElectricCar(Car):…
my_electric_car.py
from car import ElectricCar
my_tesla=ElectricCar(‘tesla’,’model s’,2020)
从一个模块中导入多个类
from car import Car,ElectricCar
导入整个模块
import car
导入模块中的所有类
from car import *
在一个模块中导入另一个模块
electric_car.py
from car import Car
参考书籍:《Python编程从入门到实践》