[关闭]
@chenwei123 2018-02-07T07:08:48.000000Z 字数 4357 阅读 363

输入、函数、类、继承

Python


输入

  1. message = input("Tell me something, and I will repeat it back to you:")
  2. print(message)
  3. #input(),接受一个参数,即向用户显示的说明描述
  4. #int()获取数值输入
  5. age = input("How old are you?") #返回的是一个字符串, 要想使用一个数值,需要用 int()
  6. print(age)
  7. age = int(age)
  8. print(age)

python2.7 输入。raw_input()提示用户输入,输入解读为字符串

函数

1.位置实参

  1. def describe_pet(animal_type, pet_name):
  2. """显示宠物信息"""
  3. print("\nI have a " + animal_type + ".")
  4. print("My " + animal_type + "'s name is " + pet_name.title() + ".")
  5. describe_pet("dog", "willie")
  6. describe_pet("willie", "dog")

注意:函数调用中实参的顺序要与函数定义中形参的顺序保持一致

2.关键字实参

  1. def describe_pet(animal_type, pet_name):
  2. """显示宠物的信息"""
  3. print("\nI hava a "+ animal_type+".")
  4. print("My "+animal_type+"'s name is "+pet_name.title()+".")
  5. describe_pet(animal_type="dog", pet_name="willie")
  6. describe_pet(pet_name="willie", animal_type="dog")

关键字实参是传递给函数的名称-值对,在实参中将名称和值关联起来。关键字实参无需考虑函数调用中实参的顺序

3. 默认值

  1. def describe_pet(pet_name, animal_type="dog"):
  2. """显示宠物的信息"""
  3. print("\nI have a "+animal_type+".")
  4. print("My "+animal_type+"'s name is "+pet_name.title()+".")
  5. describe_pet(pet_name="willie")
  6. describe_pet("willie")
  7. describe_pet(pet_name="willie", animal_type="cat")
  8. describe_pet(animal_type="cat", pet_name="willie")
  9. describe_pet("willie", "cat")

函数调用中,如果给形参提供了实参时,将使用指定的实参值;否则,将使用形参的默认值

4. 传递任意数量实参

  1. def make_pizza(*toppings):
  2. """打印顾客点的所有配料"""
  3. print(toppings)
  4. make_pizza("aa")
  5. make_pizza("aa", "bb", "cc")

形参*toppings 中的星号是让 Python 创建一个名为toppings 的空元组,并将所有收到的值封装到这个元组中。

5. 传递任意数量的关键字实参

  1. def build_profile(first,last,**user_info):
  2. """创建一个字典,其中包含我们知道的有关用户的一切"""
  3. profile={}
  4. profile["first_name"] = first
  5. profile["last_name"] = last
  6. for key, value in user_info.items():
  7. profile[key] = value
  8. user_profile = build_profile("albert", "einstein", location="princeton", field="physics")
  9. print(user_profile)

形参 **user_info 中的两个星号让 Python 创建一个名为 user_info的空字典,并将收到的所有名称-值对都封装到这个字典中。

模块

1. 导入整个模块

  1. #pizza.py
  2. def make_pizza(size, *toppings):
  3. """概述要制作的比萨"""
  4. print("\nMaking a " + str(size)+"-inch pizza with the following toppings:")
  5. for topping in toppings:
  6. print("- "+topping)
  7. #pizza.py 同目录下创建making_pizza.py
  8. import pizza
  9. pizza.make_pizza(16, "aa")
  10. pizza.make_pizza(12, "aa", "cc", "dd")

通用语法:module_name.function_name()

2. 导入特定的函数

  1. from pizza import make_pizza
  2. make_pizza(16, "aa")
  3. make_pizza(12, "aa", "cc", "dd")

3. as 给函数指定别名

  1. from pizza import make_pizza as mp
  2. mp(16, "aa")
  3. mp(12, "aa", "cc", "dd")

如果要导入的函数的名称可能与程序中现有的名称冲突,或者函数的名称太长,可指定简短而独一无二的别名。

4. as 给模块指定别名

  1. import pizza as p
  2. p.make_pizza(16, "aa")
  3. p.make_pizza(12, "aa", "cc", "dd")

5. 导入模块中所有函数

  1. from pizza import *

1. 创建类

  1. class Dog():
  2. """一次模拟小狗的简单尝试"""
  3. def __init__(self, name, age):
  4. """初始化属性 name 和 age"""
  5. self.name = name
  6. self.age = age
  7. def sit(self):
  8. """模拟小狗被命令时蹲下"""
  9. print(self.name.title() + " is now sitting.")
  10. def roll_over(self):
  11. """模拟小狗被命令时打滚"""
  12. print(self.name.title() + " rolled over!")
  13. def update_dog(self, name):
  14. """修改属性name值"""
  15. self.name = name

补充说明:Python2.7创建类时,需要在括号内包含单词 object 。类似如: class Dog(object)

2. 创建实例

  1. my_dog = Dog("willie", 6)

3. 继承

  1. class Car():
  2. """一次模拟汽车的简单尝试"""
  3. def __init__(self, make, model, year):
  4. self.make = make
  5. self.model = model
  6. self.year = year
  7. self.odometer_reading = 0
  8. def get_descriptive_name(self):
  9. long_name = str(self.year)+" "+self.make+" "+self.model
  10. return long_name.title()
  11. def read_odometer(self, mileage):
  12. print("This car has " + str(self.odometer_reading) + " miles on it.")
  13. def update_odometer(self, mileage):
  14. if mileage >= self.odometer_reading:
  15. self.odometer_reading = mileage
  16. else:
  17. print("You can't roll back on odometer!")
  18. def increment_odometer(self, miles):
  19. self.odometer_reading += miles
  20. def run(self):
  21. print("汽车在跑")
  22. class Battery():
  23. """将电瓶这部分独立出来作为一个类"""
  24. def __init__(self, battery_size=70):
  25. self.battery_size = battery_size
  26. def describe_battery(self):
  27. print("This car has a " + str(self.battery_size) + "-kwh battery.")
  28. class ElectricCar(Car):
  29. """电动汽车的独特之处"""
  30. def __init__(self, make, model, year):
  31. """初始化父类的属性,再初始化电动汽车特有的属性"""
  32. super().__init__(make, model, year)
  33. self.battery_size = 70 #子类添加新属性self.battery_size
  34. self.battery = Battery() #将实例Battery()用作ElectricCar的属性self.battery
  35. def describe_battery(self):
  36. """打印一条描述电瓶容量的消息, 子类添加新方法describe_battery"""
  37. print("This car has a " + str(self.battery_size) + "-kwh battery.")
  38. def run(self):
  39. """重写父类方法run"""
  40. print("电动汽车在跑")
  41. my_tesla = ElectricCar("tesla", "models", 2016)
  42. print(my_tesla.get_descriptive_name())
  43. my_tesla.describe_battery()

创建子类时,父类与子类必须同处一个文件中,并且父类在子类前面。定义子类时,必须在括号里指明父类的名称。super(),将父类和子类关联起来。

注意: Python2.7继承语法如下

  1. class Car(object):
  2. def __init__(self, make, model, year):
  3. --snip--
  4. class ElectricCar(Car):
  5. def __init__(self, make, model, year):
  6. super(ElectricCar, self).__init__(make, model, year)
  7. --snip--

super()需要两个实参:子类名和对象 self。父类在括号里指定object

三个引号表示文档注释

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注