输入、函数、类、继承
输入
message = input("Tell me something, and I will repeat it back to you:")
print(message)
#input(),接受一个参数,即向用户显示的说明描述
#int()获取数值输入
age = input("How old are you?") #返回的是一个字符串, 要想使用一个数值,需要用 int()
print(age)
age = int(age)
print(age)
python2.7
输入。raw_input()
提示用户输入,输入解读为字符串
函数
1.位置实参
def describe_pet(animal_type, pet_name):
"""显示宠物信息"""
print("\nI have a " + animal_type + ".")
print("My " + animal_type + "'s name is " + pet_name.title() + ".")
describe_pet("dog", "willie")
describe_pet("willie", "dog")
注意:函数调用中实参的顺序要与函数定义中形参的顺序保持一致
2.关键字实参
def describe_pet(animal_type, pet_name):
"""显示宠物的信息"""
print("\nI hava a "+ animal_type+".")
print("My "+animal_type+"'s name is "+pet_name.title()+".")
describe_pet(animal_type="dog", pet_name="willie")
describe_pet(pet_name="willie", animal_type="dog")
关键字实参是传递给函数的名称-值对,在实参中将名称和值关联起来。关键字实参无需考虑函数调用中实参的顺序
3. 默认值
def describe_pet(pet_name, animal_type="dog"):
"""显示宠物的信息"""
print("\nI have a "+animal_type+".")
print("My "+animal_type+"'s name is "+pet_name.title()+".")
describe_pet(pet_name="willie")
describe_pet("willie")
describe_pet(pet_name="willie", animal_type="cat")
describe_pet(animal_type="cat", pet_name="willie")
describe_pet("willie", "cat")
函数调用中,如果给形参提供了实参时,将使用指定的实参值;否则,将使用形参的默认值
4. 传递任意数量实参
def make_pizza(*toppings):
"""打印顾客点的所有配料"""
print(toppings)
make_pizza("aa")
make_pizza("aa", "bb", "cc")
形参
*toppings
中的星号是让 Python 创建一个名为toppings 的空元组,并将所有收到的值封装到这个元组中。
5. 传递任意数量的关键字实参
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
user_profile = build_profile("albert", "einstein", location="princeton", field="physics")
print(user_profile)
形参
**user_info
中的两个星号让 Python 创建一个名为 user_info的空字典,并将收到的所有名称-值对都封装到这个字典中。
模块
1. 导入整个模块
#pizza.py
def make_pizza(size, *toppings):
"""概述要制作的比萨"""
print("\nMaking a " + str(size)+"-inch pizza with the following toppings:")
for topping in toppings:
print("- "+topping)
#pizza.py 同目录下创建making_pizza.py
import pizza
pizza.make_pizza(16, "aa")
pizza.make_pizza(12, "aa", "cc", "dd")
通用语法:
module_name.function_name()
2. 导入特定的函数
from pizza import make_pizza
make_pizza(16, "aa")
make_pizza(12, "aa", "cc", "dd")
3. as 给函数指定别名
from pizza import make_pizza as mp
mp(16, "aa")
mp(12, "aa", "cc", "dd")
如果要导入的函数的名称可能与程序中现有的名称冲突,或者函数的名称太长,可指定简短而独一无二的别名。
4. as 给模块指定别名
import pizza as p
p.make_pizza(16, "aa")
p.make_pizza(12, "aa", "cc", "dd")
5. 导入模块中所有函数
from pizza import *
类
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!")
def update_dog(self, name):
"""修改属性name值"""
self.name = name
补充说明:Python2.7创建类时,需要在括号内包含单词 object 。类似如:
class Dog(object)
2. 创建实例
my_dog = Dog("willie", 6)
- 访问属性
my_dog.name, my_dog.age
- 调用方法
my_dog.sit(), my_dog.roll_over()
- 修改属性的值
- 直接改
my_dog.name = "Mary"
- 通过方法改
my_dog.update_dog("mary")
- 直接改
3. 继承
class Car():
"""一次模拟汽车的简单尝试"""
def __init__(self, make, model, year):
self.make = make
self.model = model
self.year = year
self.odometer_reading = 0
def get_descriptive_name(self):
long_name = str(self.year)+" "+self.make+" "+self.model
return long_name.title()
def read_odometer(self, mileage):
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 on odometer!")
def increment_odometer(self, miles):
self.odometer_reading += miles
def run(self):
print("汽车在跑")
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_size = 70 #子类添加新属性self.battery_size
self.battery = Battery() #将实例Battery()用作ElectricCar的属性self.battery
def describe_battery(self):
"""打印一条描述电瓶容量的消息, 子类添加新方法describe_battery"""
print("This car has a " + str(self.battery_size) + "-kwh battery.")
def run(self):
"""重写父类方法run"""
print("电动汽车在跑")
my_tesla = ElectricCar("tesla", "models", 2016)
print(my_tesla.get_descriptive_name())
my_tesla.describe_battery()
创建子类时,父类与子类必须同处一个文件中,并且父类在子类前面。定义子类时,必须在括号里指明父类的名称。super(),将父类和子类关联起来。
注意: Python2.7继承语法如下
class Car(object):
def __init__(self, make, model, year):
--snip--
class ElectricCar(Car):
def __init__(self, make, model, year):
super(ElectricCar, self).__init__(make, model, year)
--snip--
super()需要两个实参:子类名和对象 self。父类在括号里指定object
三个引号表示文档注释