第九章:类
9.1 创建和使用类
9.1.1 创建dog类
class Dog():
"""一次模拟小狗的简单尝试"""
def __init__(self, name, age):
"""初始化属性name,age"""
self.name = name
self.age = age
def sit(self):
"""模拟小狗搜狐到命令时蹲下"""
print(f"{self.name} is now sitting.")
def roll_over(self):
"""模拟小狗收到命令时打滚"""
print(f"{self.name} rolled over!")
my_dog = Dog('willie', 6)
print(f"My dog's name is {my_dog.name.title()}")
print(f"My dog is {my_dog.age} years old.")
类中的方法__init__(self, )极为重要,self是指向实例本身的引用。
9.1.2 根据类创建实例
访问属性:my_dog.name
调用方法:my_dog.sit()、my_dog.roll_over()
创建多个实例:my_dog = Dog(‘Willie’, 6)、your_dog = Dog(‘Lucy’, 3)
9.2 使用类和实例
9.2.1 Car类
class Car():
"""一次模拟汽车的简单尝试"""
def __init__(self, make, model, year):
"""初始化模拟汽车的属性"""
self.make = make
self.model = model
self.year = year
def get_descriptive_name(self):
"""返回整洁的描述性信息"""
long_name = f"{self.year} {self.make}, {self.model}"
return long_name.title()
my_new_car = Car('audi', 'a4', 2019)
print(my_new_car.get_descriptive_name())
9.2.2 给属性指定默认值
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 = f"{self.year} {self.make} {self.model}"
return long_name
def read_odometer(self):
"""打印一条指出汽车里程的消息"""
print(f"This car has {self.odometer_reading} miles on it.")
my_new_car = Car('audi', 'a4', 2019)
print(my_new_car.get_descriptive_name())
my_new_car.read_odometer()
9.2.3 修改属性的值
直接修改:
my_new_car.odometer_reading = 23
my_new_car.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 = f"{self.year} {self.make} {self.model}"
return long_name.title()
def read_odometer(self):
"""打印一条指出汽车里程的消息"""
print(f"This car has {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!")
my_new_car = Car('audi', 'a4', 2019)
print(my_new_car.get_descriptive_name())
my_new_car.update_odometer(-10)
my_new_car.read_odometer()
9.3 继承
9.3.1 子类的方法init()
父类Car的代码在上面已经给出
class ElectricCar(Car):
"""电动汽车"""
def __init__(self, make, model, year):
"""初始化父类的属性"""
super().__init__(make, model, year)
my_tesla = ElectricCar('tesla', 'model s', 2019)
print('\n' + my_tesla.get_descriptive_name())
9.3.2 给予类定义属性和方法
class ElectricCar(Car):
"""电动汽车"""
def __init__(self, make, model, year):
"""初始化父类的属性"""
super().__init__(make, model, year)
# 设置初始值
self.battery_size = 75
def describe_battery(self):
print(f"This car has a {self.battery_size} -kwh battery.")
my_tesla = ElectricCar('tesla', 'model s', 2019)
print(my_tesla.get_descriptive_name())
my_tesla.describe_battery()
9.3.3 重写父类的方法
在子类中定义与父类重名的方法,实例调用是会按照子类中的方法执行