一.创建和使用类

1.创建Dog类

  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!")

方法init()

方法init() 是一个特殊的方法,每当你根据Dog 类创建新实例时,Python都会自动运行它。在这个方法的名称中,开头和末尾各有两个下划线,这是一种约定,旨在避免Python默认方法与普通方法发生名称冲突。 方法init() 定义成了包含三个形参:self 、name 和age 。在这个方法的定义中,形参self 必不可少,还必须位于其他形参的前面。以self 为前缀的变量都可供类中的所有方法使用,我们还可以通过类的任何实例来访问这些变量。

2.根据类创建实例

  1. class Dog():
  2. --snip-
  3. my_dog = Dog('willie', 6)
  4. print("My dog's name is " + my_dog.name.title() + ".")
  5. print("My dog is " + str(my_dog.age) + " years old.")

1.访问属性

  1. my_dog.name

2.调用方法

  1. class Dog():
  2. --snip-
  3. my_dog = Dog('willie', 6)
  4. my_dog.sit()
  5. my_dog.roll_over()

3.创建多个实例

  1. class Dog():
  2. --snip-
  3. my_dog = Dog('willie', 6)
  4. your_dog = Dog('lucy', 3)
  5. print("My dog's name is " + my_dog.name.title() + ".")
  6. print("My dog is " + str(my_dog.age) + " years old.")
  7. my_dog.sit()
  8. print("\nYour dog's name is " + your_dog.name.title() + ".")
  9. print("Your dog is " + str(your_dog.age) + " years old.")
  10. your_dog.sit()

二.使用类和实例

1.Car类

  1. class Car():
  2. """一次模拟汽车的简单尝试"""
  3. def __init__(self, make, model, year):
  4. """初始化描述汽车的属性"""
  5. self.make = make
  6. self.model = model
  7. self.year = year
  8. def get_descriptive_name(self):
  9. """返回整洁的描述性信息"""
  10. long_name = str(self.year) + ' ' + self.make + ' ' + self.model
  11. return long_name.title()
  12. my_new_car = Car('audi', 'a4', 2016)
  13. print(my_new_car.get_descriptive_name())

2.给属性指定默认值

  1. class Car():
  2. def __init__(self, make, model, year):
  3. """初始化描述汽车的属性"""
  4. self.make = make
  5. self.model = model
  6. self.year = year
  7. self.odometer_reading = 0
  8. def get_descriptive_name(self):
  9. --snip-
  10. def read_odometer(self):
  11. """打印一条指出汽车里程的消息"""
  12. print("This car has " + str(self.odometer_reading) + " miles on it.")
  13. my_new_car = Car('audi', 'a4', 2016)
  14. print(my_new_car.get_descriptive_name())
  15. my_new_car.read_odometer()

3.修改属性的值

1.直接修改属性的值

  1. class Car():
  2. --snip-
  3. my_new_car = Car('audi', 'a4', 2016)
  4. print(my_new_car.get_descriptive_name())
  5. my_new_car.odometer_reading = 23
  6. my_new_car.read_odometer()

2.通过方法修改属性的值

  1. class Car():
  2. --snip-
  3. def update_odometer(self, mileage):
  4. """将里程表读数设置为指定的值"""
  5. self.odometer_reading = mileage
  6. my_new_car = Car('audi', 'a4', 2016)
  7. print(my_new_car.get_descriptive_name())
  8. my_new_car.update_odometer(23)
  9. my_new_car.read_odometer()

3.通过方法对属性的值进行递增

  1. class Car():
  2. --snip-
  3. def update_odometer(self, mileage):
  4. --snip-
  5. def increment_odometer(self, miles):
  6. """将里程表读数增加指定的量"""
  7. self.odometer_reading += miles
  8. my_used_car = Car('subaru', 'outback', 2013)
  9. print(my_used_car.get_descriptive_name())
  10. my_used_car.update_odometer(23500)
  11. my_used_car.read_odometer()
  12. my_used_car.increment_odometer(100)
  13. my_used_car.read_odometer()

三.继承

1.子类的方法init()

  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):
  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 an odometer!")
  18. def increment_odometer(self, miles):
  19. self.odometer_reading += miles
  20. class ElectricCar(Car):
  21. """电动汽车的独特之处"""
  22. def __init__(self, make, model, year):
  23. """初始化父类的属性"""
  24. super().__init__(make, model, year)
  25. my_tesla = ElectricCar('tesla', 'model s', 2016)
  26. print(my_tesla.get_descriptive_name())

2.给子类定义属性和方法

  1. class Car():
  2. --snip-
  3. class ElectricCar(Car):
  4. """Represent aspects of a car, specific to electric vehicles."""
  5. def __init__(self, make, model, year):
  6. """
  7. 电动汽车的独特之处
  8. 初始化父类的属性,再初始化电动汽车特有的属性
  9. """
  10. super().__init__(make, model, year)
  11. self.battery_size = 70
  12. def describe_battery(self):
  13. """打印一条描述电瓶容量的消息"""
  14. print("This car has a " + str(self.battery_size) + "-kWh battery.")
  15. my_tesla = ElectricCar('tesla', 'model s', 2016)
  16. print(my_tesla.get_descriptive_name())
  17. my_tesla.describe_battery()

3.重写父类的方法

对于父类的方法,只要它不符合子类模拟的实物的行为,都可对其进行重写。

  1. class ElectricCar(Car):
  2. --snip-
  3. def fill_gas_tank():
  4. """电动汽车没有油箱"""
  5. print("This car doesn't need a gas tank!")

4.将实例用作属性

  1. class Car():
  2. --snip-
  3. class Battery():
  4. """一次模拟电动汽车电瓶的简单尝试"""
  5. def __init__(self, battery_size=70):
  6. """初始化电瓶的属性"""
  7. self.battery_size = battery_size
  8. def describe_battery(self):
  9. """打印一条描述电瓶容量的消息"""
  10. print("This car has a " + str(self.battery_size) + "-kWh battery.")
  11. class ElectricCar(Car):
  12. """电动汽车的独特之处"""
  13. def __init__(self, make, model, year):
  14. """
  15. 初始化父类的属性,再初始化电动汽车特有的属性
  16. """
  17. super().__init__(make, model, year)
  18. self.battery = Battery()
  19. my_tesla = ElectricCar('tesla', 'model s', 2016)
  20. print(my_tesla.get_descriptive_name())
  21. my_tesla.battery.describe_battery()

四.导入类

1.导入单个类

  1. """一个可用于表示汽车的类"""
  2. class Car():
  3. """一次模拟汽车的简单尝试"""
  4. def __init__(self, make, model, year):
  5. """初始化描述汽车的属性"""
  6. self.make = make
  7. self.model = model
  8. self.year = year
  9. self.odometer_reading = 0
  10. def get_descriptive_name(self):
  11. """返回整洁的描述性名称"""
  12. long_name = str(self.year) + ' ' + self.make + ' ' + self.model
  13. return long_name.title()
  14. def read_odometer(self):
  15. """打印一条消息,指出汽车的里程"""
  16. print("This car has " + str(self.odometer_reading) + " miles on it.")
  17. def update_odometer(self, mileage):
  18. """
  19. 将里程表读数设置为指定的值
  20. 拒绝将里程表往回拨
  21. """
  22. if mileage >= self.odometer_reading:
  23. self.odometer_reading = mileage
  24. else:
  25. print("You can't roll back an odometer!")
  26. def increment_odometer(self, miles):
  27. """将里程表读数增加指定的量"""
  28. self.odometer_reading += miles
  1. from car import Car
  2. my_new_car = Car('audi', 'a4', 2016)
  3. print(my_new_car.get_descriptive_name())
  4. my_new_car.odometer_reading = 23
  5. my_new_car.read_odometer()

2.在一个模块中存储多个类

  1. """一组用于表示燃油汽车和电动汽车的类"""
  2. class Car():
  3. --snip-
  4. class Battery():
  5. """一次模拟电动汽车电瓶的简单尝试"""
  6. def __init__(self, battery_size=60):
  7. """初始化电瓶的属性"""
  8. self.battery_size = battery_size
  9. def describe_battery(self):
  10. """打印一条描述电瓶容量的消息"""
  11. print("This car has a " + str(self.battery_size) + "-kWh battery.")
  12. def get_range(self):
  13. """打印一条描述电瓶续航里程的消息"""
  14. if self.battery_size == 70:
  15. range = 240
  16. elif self.battery_size == 85:
  17. range = 270
  18. message = "This car can go approximately " + str(range)
  19. message += " miles on a full charge."
  20. print(message)
  21. class ElectricCar(Car):
  22. """模拟电动汽车的独特之处"""
  23. def __init__(self, make, model, year):
  24. """
  25. 初始化父类的属性,再初始化电动汽车特有的属性
  26. """
  27. super().__init__(make, model, year)
  28. self.battery = Battery()
  1. from car import ElectricCar
  2. my_tesla = ElectricCar('tesla', 'model s', 2016)
  3. print(my_tesla.get_descriptive_name())
  4. my_tesla.battery.describe_battery()
  5. my_tesla.battery.get_range()

3.从一个模块中导入多个类

  1. from car import Car, ElectricCar
  2. my_beetle = Car('volkswagen', 'beetle', 2016)
  3. print(my_beetle.get_descriptive_name())
  4. my_tesla = ElectricCar('tesla', 'roadster', 2016)
  5. print(my_tesla.get_descriptive_name())

4.导入整个模块

  1. import car
  2. my_beetle = car.Car('volkswagen', 'beetle', 2016)
  3. print(my_beetle.get_descriptive_name())
  4. my_tesla = car.ElectricCar('tesla', 'roadster', 2016)
  5. print(my_tesla.get_descriptive_name())

5.导入模块中的所有类

  1. from module_name import *

6.在一个模块中导入另一个模块

  1. from car import Car
  2. class Battery():
  3. --snip-
  4. class ElectricCar(Car):
  5. --snip-
  1. """一个可用于表示汽车的类"""
  2. class Car():
  3. --snip-
  1. from car import Car
  2. from electric_car import ElectricCar
  3. my_beetle = Car('volkswagen', 'beetle', 2016)
  4. print(my_beetle.get_descriptive_name())
  5. my_tesla = ElectricCar('tesla', 'roadster', 2016)
  6. print(my_tesla.get_descriptive_name())