使用类几乎可以模拟任何东西。下面来编写一个表示小狗的简单类Dog——它表示的不是特 定的小狗,而是任何小狗。
根据Dog类创建的每个实例都将存储名字和年龄。我们赋予了每条小狗蹲下sit()和打滚 roll_over()的能力:
class Dog(): """一次模拟小狗的简单尝试""" def __init__(self, name, age): """初始化属性name和age""" self.name = name self.age = age def sit(self): """模拟小狗被命令时蹲下""" print(self.name.title() + "快蹲下!") def roll_over(self): """模拟小狗被命令时打滚""" print(self.name.title() + "打个滚!")
下面来创建一个表示特定小狗的实例:
my_dog = Dog("小黑", 6)
print("我狗的名字叫:" + my_dog.name.title() + ".") print("我的狗已经" + str(my_dog.age) + "了.")
my_dog.sit() my_dog.roll_over()
my_dog = Dog('willie', 6) your_dog = Dog('lucy', 3)
下面来编写一个表示汽车的类,它存储了有关汽车的信息,还有一个汇总这些信息的方法:
class Car(): """一次模拟汽车的简单尝试""" def __init__(self, make, model, year): """初始化描述汽车的属性""" self.make = make self.model = model self.year = year def get_descriptive_name(self): """返回整洁的描述性信息""" long_name = str(self.year) + ' ' + self.make + ' ' + self.model return long_name.title() my_new_car = Car('audi', 'a4', 2016) print(my_new_car.get_descriptive_name())
下面来添加一个名为odometer_reading的属性,其初始值总是为0。我们还添加了一个名为 read_odometer()的方法,用于读取汽车的里程表:
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): """打印一条指出汽车里程的消息""" print("This car has " + str(self.odometer_reading) + " miles on it.") my_new_car = Car('audi', 'a4', 2016) print(my_new_car.get_descriptive_name()) my_new_car.read_odometer()
- List item my_new_car.odometer_reading = 23 my_new_car.read_odometer()
def update_odometer(self, mileage): """ 将里程表读数设置为指定的值 禁止将里程表读数往回调 """ if mileage >=self.odometer_reading: self.odometer_reading = mileage else: print("You can't roll back an odometer!") my_new_car.update_odometer(23) my_new_car.read_odometer()
def increment_odometer(self, miles): """将里程表读数增加指定的量""" self.odometer_reading += miles my_new_car.update_odometer(2000) my_new_car.increment_odometer(500) my_new_car.read_odometer()
一个类继承另一个类时,它将自动获得另一个类的所有属性和方法;原有的类称为父类, 而新类称为子类
创建子类的实例时,Python首先需要完成的任务是给父类的所有属性赋值。为此,子类的方法__init__()需要父类施以援手
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): 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
class ElectricCar(Car): """电动汽车的独特之处""" def __init__(self,make, model, year): """初始化父类的属性""" super().__init__(make, model, year)
my_tesla = ElectricCar('tesla', 'model s', 2016)
print(my_tesla.get_descriptive_name())
self.battery_size = 70
def describe_battery(self): """打印一条描述电瓶容量的消息""" print("This car has a " + str(self.battery_size) + "-kWh battery.")
my_tesla.describe_battery()
对于父类的方法,只要它不符合子类模拟的实物的行为,都可对其进行重写。
假设Car类有一个名为fill_gas_tank()的方法,它对全电动汽车来说毫无意义,因此你可能 想重写它。
下面演示了一种重写方式:
def fill_gas_tank(): """电动汽车没有油箱""" print("This car doesn't need a gas tank!") my_tesla = ElectricCar('tesla', 'model s', 2016)
将类的一部分作为一个独立的类提取出来。你可以将大 型类拆分成多个协同工作的小类
不断给ElectricCar类添加细节时,我们可能会发现其中包含很多专门针对汽车电瓶 的属性和方法。在这种情况下,我们可将这些属性和方法提取出来,放到另一个名为Battery的 类中,并将一个Battery实例用作ElectricCar类的一个属性:
self.battery = Battery()
注:这行代码让Python 创建一个新的Battery实例
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") def fill_gas_tank(self): """电动汽车没有油箱""" print("This car doesn't need a gas tank!")
my_tesla.battery.describe_battery()
注:这行代码让Python在实例my_tesla中查找属性battery,并对存储在该属性中的Battery实例调用方法describe_battery()
def get_range(self): """打印一条消息,指出电瓶的续航里程""" if self.battery_size == 70: range = 240 elif self.battery_size == 85: range = 270 message = "This car can go approximately " + str(range) + " miles on a full charge." print(message)
my_tesla.battery.get_range()
为遵循 Python的总体理念,应让文件尽可能整洁。为在这方面提供帮助,Python允许你将类存储在模块 中,然后在主程序中导入所需的模块。
"""一个可用于表示汽车的类""" 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): """打印一条消息,指出汽车的里程""" 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
from car import Car my_new_car = Car('audi', 'a4', 2016) print(my_new_car.get_descriptive_name()) my_new_car.odometer_reading = 23 my_new_car.read_odometer()
类Battery和ElectricCar都可帮助模拟汽车,因此下面将它们都加入模块car.py中
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") def fill_gas_tank(self): """电动汽车没有油箱""" print("This car doesn't need a gas tank!") def get_range(self): """打印一条消息,指出电瓶的续航里程""" if self.battery_size == 70: range = 240 elif self.battery_size == 85: range = 270 message = "This car can go approximately " + str(range) + " miles on a full charge." print(message) class ElectricCar(Car): """模拟电动汽车的独特之处""" def __init__(self, make, model, year): """ 初始化父类的属性,再初始化电动汽车特有的属性 """ super().__init__(make, model, year) self.battery = Battery()
新建一个名为my_electric_car.py的文件,导入ElectricCar类,并创建一辆电动汽车了:
from car import ElectricCar my_tesla = ElectricCar('tesla', 'model s', 2016) print(my_tesla.get_descriptive_name()) my_tesla.battery.describe_battery() my_tesla.battery.get_range()
from car import Car, ElectricCar
import car my_beetle = car.Car('volkswagen', 'beetle', 2016) print(my_beetle.get_descriptive_name()) my_tesla = car.ElectricCar('tesla', 'roadster', 2016) print(my_tesla.get_descriptive_name())