Chapter 08:函数

定义函数

def greet_user(name):
    print("Hello, " + name.title() + '!')
    
greet_user('jesse')

Hello, Jesse!

关键字实参使得实参的传递不必严格按照形参的顺序

def describe_pet(animal_type, pet_name):
    print("I have a " + animal_type + ".")
    print("My " + animal_type + "'s name is " + pet_name.title() + ".")

describe_pet(animal_type='hamster', pet_name='harry')

I have a hamster.
My hamster's name is Harry.

带默认值的形参,显然有默认值的形参在参数列表中排在无默认值形参的后面

def describe_pet(pet_name, animal_type='dog'):
    print("I have a " + animal_type + ".")
    print("My " + animal_type + "'s name is " + pet_name.title() + ".")

describe_pet('harry')

I have a dog.
My dog's name is Harry.

简单返回值的函数

def get_formmatted_name(first_name, last_name):
    full_name = first_name + ' ' + last_name
    return full_name.title()

print(get_formmatted_name('jimi','hendrix'))

Jimi Hendrix

函数可返回任何类型的值,包括列表和字典

def build_person(first_name,last_name,age=''):
    person = {'first': first_name, 'last': last_name}
    if age:
        person['age'] = age
    return person

musician = build_person('jimi','hendrix',age=27)
print(musician)

{'first': 'jimi', 'last': 'hendrix', 'age': 27}

传递列表并修改

def greet_users(names):
    for i in range(len(names)):
        names[i] = names[i].title()
        
usernames = ['hannah', 'ty', 'margot']
greet_users(usernames)
print(usernames)

['Hannah', 'Ty', 'Margot']

当不打算改变原列表时,可传入列表的副本

def greet_users(names):
    for i in range(len(names)):
        names[i] = names[i].title()
        
usernames = ['hannah', 'ty', 'margot']
greet_users(usernames[:])
print(usernames)

['hannah', 'ty', 'margot']

传递任意数量的实参

def make_pizza(*toppings): #toppings 是一个元组
    for topping in toppings:
        print(topping)
    
make_pizza('pepperoni')
make_pizza('mushroooms','green peppers','extra cheese')

pepperoni
mushroooms
green peppers
extra cheese

结合使用位置实参和任意数量实参

def make_pizza(size, *toppings):
    print("\nMaking a " + str(size) + "-inch pizza with the following toppings:")
    for topping in toppings:
        print("- " + topping)

make_pizza(16, 'pepperoni')
make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')

Making a 16-inch pizza with the following toppings:
- pepperoni

Making a 12-inch pizza with the following toppings:
- mushrooms
- green peppers
- extra cheese

使用任意数量的关键字实参,很多库的API都这么设计

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_profile1 = build_profile('albert','einstein',
                            location='princton',field='physics')
user_profile2 = build_profile('marie','curie',
                              user_info={'location':'paris','field':'pthsics'})
#不能这么写
#user_profile2 = build_profile('marie','curie',
#                              {'location':'paris','field':'pthsics'})
u3info = {'location': 'london','field': 'computer'}
user_profile3 = build_profile('turing','alen',**u3info)

print(user_profile1)
print(user_profile2)
print(user_profile3)

{'first_name': 'albert', 'last_name': 'einstein', 'location': 'princton', 'field': 'physics'}
{'first_name': 'marie', 'last_name': 'curie', 'user_info': {'location': 'paris', 'field': 'pthsics'}}
{'first_name': 'turing', 'last_name': 'alen', 'location': 'london', 'field': 'computer'}

将函数存储为单独的模块

将pizza.py与making_pizzas.py置于同一目录

pizza.py内容

def make_pizza(size, *toppings):
    print("\nMaking a "+str(size) + '-inch pizza with the following toppings:')
    for topping in toppings:
        print('-' + topping)

making_pizzas.py 通过 import 导入 pizza 模块

import pizza
pizza.make_pizza(16, 'pepperoni')
pizza.make_pizza(12, 'mushrooms', 'green pepers', 'extra cheese')

导入特定的函数

from pizza import make_pizza
make_pizza(16, 'pepperoni')
make_pizza(12, 'mushrooms', 'green pepers', 'extra cheese')

使用as给函数指定别名

from pizza import make_pizza as mp
mp(16, 'pepperoni')
mp(12, 'mushrooms', 'green pepers', 'extra cheese')

as也可以给模块起别名

import pizza as p
p.make_pizza(16, 'pepperoni')
p.make_pizza(12, 'mushrooms', 'green pepers', 'extra cheese')

你可能感兴趣的:(Chapter 08:函数)