Python3 类

逆流者 2020年11月03日 111次浏览

创建和使用类

创建Dog类

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() + ' 打滚!')

分析下Dog类的结构:

  • """一次模拟小狗的简单尝试""" 文档注释, 可以放在类上, 也可以放在方法上
  • 方法 __init__()是构造方法, 它是一个特殊方法,在这个方法名称中, 开头和末尾各有两个下划线, 区别于其他方法, 当创建Dog()类的时候Python会自动运行它, 关于定义的三个形参(self, name, age), self代表类的实例,而非类, 当Python调用__init__()方法来创建实例时, 将自动的传入实参self, 每个与类相关的方法调用都自动传递实参self, 它是一个指向实例本身的引用, 让实例能够访问类中的属性和方法.

根据类创建实例

# 根据类创建实例
my_dog = Dog('哈士奇', 6)
# 访问属性 my_dog.name
print('我的狗名字是 ' + my_dog.name.title() + '.')
print('我的狗 ' + str(my_dog.age) + ' 岁了.')
# 调用方法
my_dog.sit()
my_dog.roll_over()
我的狗名字是 哈士奇.
我的狗 6 岁了.
哈士奇 现在蹲下!
哈士奇 打滚!
  • 访问属性 my_dog.name
  • 调用方法 my_dog.sit()

使用类和实例

Car类

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('The Car has ' + str(self.odometer_reading) + ' miles on it.')

    def update_odometer(self, mileage):
        """将里程表读数设置为指定的值"""
        self.odometer_reading = mileage

    def increment_odometer(self, miles):
        self.odometer_reading += miles

测试一下:

my_new_car = Car('audi', 'a4', 2016)
print(my_new_car)
print(my_new_car.get_descriptive_name())
my_new_car.read_odometer()

结果:

<__main__.Car object at 0x1037d8040>
2016 Audi A4
The Car has 0 miles on it.

给属性指定默认值

在上面构造方法中可以看到:

# 给属性指定默认值
self.odometer_reading = 0

修改属性的值

# 修改属性的值
my_new_car.odometer_reading = 23
my_new_car.read_odometer()
The Car has 23 miles on it.

通过方法修改属性的值

# 通过方法修改属性的值
my_new_car.update_odometer(30)
my_new_car.read_odometer()
The Car has 30 miles on it.

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

# 通过方法对属性的值进行递增
my_new_car.increment_odometer(10)
my_new_car.read_odometer()
The Car has 40 miles on it.

继承

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('The Car has ' + str(self.odometer_reading) + ' miles on it.')

    def update_odometer(self, mileage):
        """将里程表读数设置为指定的值"""
        self.odometer_reading = mileage

    def increment_odometer(self, miles):
        self.odometer_reading += miles

    def fill_gas_tank(self):
        """普通汽车有油箱"""
        print('This Car need a gas tank!')

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 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()

    def fill_gas_tank(self):
        """电动汽车没有油箱"""
        print('This Car doesn‘s need a gas tank!')

上面代码中有两个类, 父类是Car, 子类是ElectricCar, ElectricCar(Car)就表示子类ElectricCar继承父类Car

子类的方法__init__()

def __init__(self, make, model, year):
    super().__init__(make, model, year)

super()是一个特殊函数, 帮助Python将父类和子类关联起来

做一下测试:

my_tesla = ElectricCar('tesla', 'model s', 2016)
print(my_tesla.get_descriptive_name())
2016 Tesla Model S

重写父类的方法

def fill_gas_tank(self):
    """电动汽车没有油箱"""
    print('This Car doesn‘s need a gas tank!')

做一下测试:

# 测试 重写父类的方法
my_tesla.fill_gas_tank()
This Car doesn‘s need a gas tank!

将实例用作属性

# 将实例用作属性
self.battery = Battery()

测试一下:

# 测试 将实例用作属性
my_tesla.battery.describe_battery()
my_tesla.battery.get_range()
This Car has a 70-kwh battery.
This car can go approximately 240 miles on a full charge.

导入类

导入单个类

car.py

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('The Car has ' + str(self.odometer_reading) + ' miles on it.')

    def update_odometer(self, mileage):
        """将里程表读数设置为指定的值"""
        self.odometer_reading = mileage

    def increment_odometer(self, miles):
        self.odometer_reading += miles

my_car.py

# 导入单个类
from car import Car

my_new_car = Car('audi', 'a4', 2016)
print(my_new_car)
print(my_new_car.get_descriptive_name())
my_new_car.read_odometer()
# 修改属性的值
my_new_car.odometer_reading = 23
my_new_car.read_odometer()

测试结果:

<car.Car object at 0x100659040>
2016 Audi A4
The Car has 0 miles on it.
The Car has 23 miles on it.

在一个模块中存储多个类

electric_car.py

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('The Car has ' + str(self.odometer_reading) + ' miles on it.')

    def update_odometer(self, mileage):
        """将里程表读数设置为指定的值"""
        self.odometer_reading = mileage

    def increment_odometer(self, miles):
        self.odometer_reading += miles

    def fill_gas_tank(self):
        """普通汽车有油箱"""
        print('This Car need a gas tank!')

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 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()

    def fill_gas_tank(self):
        """电动汽车没有油箱"""
        print('This Car doesn‘s need a gas tank!')

从一个模块中导入多个类

# 从一个模块中导入多个类
from electric_car import ElectricCar, Car

导入整个模块

# 导入整个模块 需要使用 模块名.
import electric_car

my_new_car = electric_car.Car('audi', 'a4', 2016)

导入模块中所有的类

from electric_car import *

Python 标准库

Python 标准库是一组模块, 安装Python都包含它.

下面演示使用标准库中collections模块的类OrderedDict

from collections import OrderedDict

favorite_languages = OrderedDict()

favorite_languages['jen'] = 'python'
favorite_languages['sarah'] = 'c'
favorite_languages['edward'] = 'ruby'
favorite_languages['phil'] = 'python'

for name, languages in favorite_languages.items():
    print(name.title() + "'s favorite languages is " + languages.title() + '.')


Jen's favorite languages is Python.
Sarah's favorite languages is C.
Edward's favorite languages is Ruby.
Phil's favorite languages is Python.

Python3 目录

  1. Python3 教程
  2. Python3 变量和简单数据类型
  3. Python3 列表
  4. Python3 操作列表
  5. Python3 if 语句
  6. Python3 if 字典
  7. Python3 用户输入和while循环
  8. Python3 函数
  9. Python3 类
  10. Python3 文件和异常
  11. Python3 测试代码
  12. Python3 使用matplotlib绘制图表
  13. Python3 使用Pygal生成矢量图形文件
  14. Python3 使用csv模块处理CSV(逗号分割的值)格式存储的天气数据
  15. Python3 处理JSON格式数据(制作交易收盘价走势图)
  16. Python3 使用API