Python学习笔记2

#1.函数
#例1
def greet_user(username):
"""显示简单的问候语"""
print('Hello,' + username.title() + '!')
greet_user('Jesse')

#例2
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)

#例3
def build_person(first_name,last_name):
"""返回一个字典,其中包含有关一个人的信息"""
person = {'first':first_name.title(),'last':last_name.title()}
return person
musician = build_person('jimi','hendrix')
print(musician)

#例4
def print_name1(name1,name2):
while name1:
current_name = name1.pop()
print("Printing name1:" + current_name)
name2.append(current_name)
def show_name2(name2):
print("\nPrinting name2:")
for name22 in name2:
print(name22)
name1 = ['iphone','robot','dodecahedron']
name2 = []
print_name1(name1,name2)
show_name2(name2)

print_name1(name1[:],name2) #向函数传递列表的副本,禁止函数修改列表

#例5
def make_pizza(*toppings): #可传递任意数量的实参
"""打印顾客点的所有配料"""
print("\nMaking a pizza with the following toppings")
for topping in toppings:
print("- " + topping)
make_pizza('mushroom','green peppers','extra cheese')

#例6
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('albert','einstein',location='princeton',field='physics')
print(user_profile)

#例7
def make_pizza(size,*toppings):
"""概述要制作的披萨"""
print("\nMake a " + str(size) + "-inch pizza with the following toppings:")
for topping in toppings:
print("- " + topping)
#将其保存为pizza.py,且文件pizza.py中除该函数外无其他代码
import pizza #导入模块pizza,可在程序中使用该模块中所有函数
pizza.make_pizza(12,"mushrooms",'extra cheese')

from module_name import function_0,functin_1,function_2#导入特定的函数

#例8
from pizza import make_pizza as mp #指定别名mp
mp(12,"mushrooms",'extra cheese')

#例9
import pizza as p
p.make_pizza(12,"mushrooms",'extra cheese')

#例10
from pizza import * #导入模块中的所有函数
make_pizza(12,"mushrooms",'extra cheese')



#2.类
#例1
class Dog():
"""一次模拟小狗的简单尝试"""
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!")

my_dog = Dog('willie',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()

#例2
class Car():
"""一次模拟汽车的简单尝试"""
def __init__(self,make,model,year):
"""初始化描述汽车的属性"""
self.make = make
self.model = model
self.year = year
self.odometer_reading = 0 #添加属性odometer_reading,初始值为0

def get_name(self):
"""返回信息"""
long_name = str(self.year) + ' ' + self.name + ' ' + self.model
return long_name.title()

def read_odometer(self):
"""打印汽车里程信息"""
print("This car has " + str(self.odometer_reading) + " miles on it")
def update_odometer(self,mileage):
"""将里程表读书设置为指定的值,且禁止往回调"""
if mileage >= self.odometer_reading:
self.odometer_reading = mileage
else:
print("You can't roll back an odometer!")
def increment_odometer(self,miles):
"""将里程表增加指定的量"""
self.odometer_reading += miles
my_usedcar = Car('subaru','outback',2013)
print(my_usedcar.get_name())
my_usedcar.update_odometer(23500)
my_usedcar.read_odometer()
my_usedcar.increment_odometer(100)
my_usedcar.read_odometer()

#例3
class ElectricCar(Car): #继承Car
"""电动汽车的独特之处"""
def __init__(self,make,model,year):
"""初始化父类的属性"""
super()._init_(make,model,year)
self.battery_size = 70  #添加子类的新属性

def describe_battery(self): #添加子类的新方法
"""打印电瓶容量信息"""
print("This car has a " + str(self.battery_size) + "-kWh battery.")
my_tesla = ElectricCar('tesila','model s',2016)
print(my_tesla.get_name())
my_tesla.describe_battery()

#例4
#将例2的Car类保存为car.py
from car import Car #导入模块car中的类Car
my_newcar = Car('audi','a4',2016)
print(my_newcar.get_name())

#或者
import car
my_newcar = car.Car('audi','a4',2016)
print(my_newcar.get_name())

#例5
from collections import OrderedDict #导入OrderedDict类
favorite_languages = OrderedDict()  #创建空的有序字典
favorite_languages['jen'] = 'python'
favorite_languages['sarah'] = 'c'
favorite_languages['phil'] = 'ruby'

for name,language in favorite_languages.items():
print(name.title() + "'s favorite language is " + language.title() + ".")
发布了51 篇原创文章 · 获赞 108 · 访问量 26万+
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 大白 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览