目录
1.基本理论简述
类与对象
构造函数(Constructor)
继承(Inheritance)
方法重写(Method Overriding)
四者关系总结
类的文档字符串(Docstring)
2.练习开始
3.代码模块化练习
(下一节课:文件操作)
类(Class):
对象(Object):
示例:
class Dog: # 类定义
def bark(self): # 方法
print("汪汪")
my_dog = Dog() # 创建对象(实例化)
my_dog.bark() # 调用对象的方法
定义:
__init__
方法作为构造函数。作用:
示例:
class Dog:
def __init__(self, name, age): # 构造函数
self.name = name # 实例属性
self.age = age
my_dog = Dog("小白", 3) # 初始化属性
print(my_dog.name) # 输出:小白
定义:
作用:
示例:
class Animal: # 父类
def eat(self):
print("吃东西")
class Dog(Animal): # 子类继承父类
def bark(self):
print("汪汪")
my_dog = Dog()
my_dog.eat() # 继承自父类的方法
my_dog.bark() # 子类自己的方法
定义:
作用:
示例:
class Animal:
def speak(self):
print("动物发声")
class Dog(Animal):
def speak(self): # 重写父类方法
print("汪汪")
my_dog = Dog()
my_dog.speak() # 输出:汪汪(调用子类重写后的方法)
定义:类定义内部的第一个字符串,用于描述类的功能和用法。
作用:提供代码文档,可通过__doc__
属性获取。
示例:
class Calculator:
"""
简单的计算器类,支持加法和减法。
属性:
result (int): 计算结果
"""
def __init__(self):
self.result = 0
def add(self, a, b):
"""计算两个数的和"""
self.result = a + b
return self.result
print(Calculator.__doc__) # 输出类的文档字符串
# 输出:
# """
# 简单的计算器类,支持加法和减法。
#
# 属性:
# result (int): 计算结果
# """
print(Calculator.add.__doc__) # 输出方法的文档字符串
# 输出:
# """计算两个数的和"""
规范:
"""
)包裹多行文档。import time
class Microwave():
'''微波炉类的文档说明'''
def __init__(self,name):
self.name=name
self.time=time.strftime("%Y-%m-%d %H:%M:%S",time.localtime())
def print_info(self):
print(' 微波炉的名字:',self.name,'\n','购买时间:',self.time)
def bread (self,temp=3):
self.temp = temp
print(" 开始烤面包,时长:",self.temp,'分钟')
pass
a = Microwave('zhangsan')
a.print_info()
a.bread()
微波炉的名字: zhangsan
购买时间: 2024-10-12 10:00:00(此处时间根据实际运行时生成)
开始烤面包,时长: 3 分钟
Microwave
类,类中有文档说明。__init__
方法是类的构造函数,用于初始化对象的属性,包括name
和time
,time
是当前时间。print_info
方法用于打印微波炉的名字和购买时间。bread
方法用于模拟烤面包的操作,默认烤面包时长为 3 分钟。Microwave
类的对象a
,并调用了print_info
和bread
方法。import time
class Microwave():
'''微波炉类的文档说明'''
def __init__(self,name):
self.name=name
self.time=time.strftime("%Y-%m-%d %H:%M:%S",time.localtime())
def print_info(self):
print(' 微波炉的名字:',self.name,'\n','购买时间:',self.time)
def bread (self,temp=3):
self.temp = temp
print(" 开始烤面包,时长:",self.temp,'分钟')
pass
##a = Microwave('zhangsan')
##print(a.name,a.time)
##print(a.temp)
a = Microwave('zhangsan')
a.bread()
print(a.temp)
开始烤面包,时长: 3 分钟
3
Microwave
类,包含构造函数__init__
、print_info
和bread
方法。Microwave
类的对象a
,调用bread
方法开始烤面包,最后打印烤面包的时长。import time
class Microwave():
'''微波炉类的文档说明'''
def __init__(self,name):
self.name=name
self.time=time.strftime("%Y-%m-%d %H:%M:%S",time.localtime())
self.bread(10)
def print_info(self):
print(' 微波炉的名字是:',self.name,'\n','购买时间是:',self.time)
def bread (self,temp=3):
self.temp = temp
print(" 开始烤面包,时长为:",self.temp,'分钟')
pass
a = Microwave('zhangsan')
print(a.name,a.time)
print(a.temp)
开始烤面包,时长为: 10 分钟
zhangsan 2024-10-12 10:00:00(此处时间根据实际运行时生成)
10
Microwave
类的构造函数__init__
中调用了bread
方法,并传入参数 10,即烤面包时长为 10 分钟。a
时会自动执行__init__
方法,开始烤面包。name
、time
和temp
属性。import time
class Microwave():
'''微波炉类的文档说明'''
def __init__(self,name):
self.name=name
self.time=time.strftime("%Y-%m-%d %H:%M:%S",time.localtime())
def print_info(self):
print(' 微波炉的名字是:',self.name,'\n','购买时间是:',self.time)
def bread (self,temp=3):
self.temp = temp
print(" 开始烤面包,时长为:",self.temp,'分钟')
pass
a = Microwave('zhangsan')
a.name = 'lisi'
a.time = '2022年6月7日'
print(a.name,a.time)
lisi 2022年6月7日
Microwave
类,包含构造函数和相关方法。a
后,修改了对象的name
和time
属性,最后打印修改后的属性值。import time
class Microwave():
'''微波炉类的文档说明
微波炉类的文档说明'''
def __init__(self,name):
self.name=name
self.time=time.strftime("%Y-%m-%d %H:%M:%S",time.localtime())
def print_info(self):
print(' 微波炉的名字是:',self.name,'\n','购买时间是:',self.time)
def bread (self,temp=3):
self.temp = temp
print(" 开始烤面包,时长为:",self.temp,'分钟')
pass
a = Microwave('zhangsan')
print(a.__doc__)
微波炉类的文档说明
微波炉类的文档说明
Microwave
类,类中有文档说明。a
后,使用__doc__
属性打印类的文档说明。import time
class Microwave():
'''微波炉类的文档说明'''
def __init__(self,name):
self.name=name
self.time=time.strftime("%Y-%m-%d %H:%M:%S",time.localtime())
def print_info(self):
print(' 微波炉的名字是:',self.name,'\n','购买时间是:',self.time)
def bread (self,temp=3):
self.temp = temp
print(" 开始烤面包,时长为:",self.temp,'分钟')
pass
class New_Microwave(Microwave):
'''从Microwave继承的子类'''
def __init__(self,name,light):
super().__init__(name)
self.light = light
a=New_Microwave('zhangsan',100)
a.print_info()
微波炉的名字是: zhangsan
购买时间是: 2024-10-12 10:00:00(此处时间根据实际运行时生成)
Microwave
类,包含构造函数和相关方法。New_Microwave
类,继承自Microwave
类,在构造函数中使用super().__init__(name)
调用父类的构造函数,并添加了light
属性。New_Microwave
类的对象a
,调用print_info
方法,该方法继承自父类。import time
class Microwave():
'''微波炉类的文档说明'''
def __init__(self,name):
self.name=name
self.time=time.strftime("%Y-%m-%d %H:%M:%S",time.localtime())
def print_info(self):
print(' 微波炉的名字是:',self.name,'\n','购买时间是:',self.time)
def bread (self,temp=3):
self.temp = temp
print(" 开始烤面包,时长为:",self.temp,'分钟')
pass
class New_Microwave(Microwave):
'''从Microwave继承的子类'''
def __init__(self,name,light):
super().__init__(name)
self.light = light
a=Microwave('zhangsan')
print(a.light)
AttributeError: 'Microwave' object has no attribute 'light'
Microwave
类和New_Microwave
类,New_Microwave
类继承自Microwave
类,New_Microwave
类有light
属性,而Microwave
类没有。Microwave
类的对象a
,尝试打印a.light
,会抛出AttributeError
异常,因为Microwave
类的对象没有light
属性。import time
class Microwave():
'''微波炉类的文档说明'''
def __init__(self,name):
self.name=name
self.time=time.strftime("%Y-%m-%d %H:%M:%S",time.localtime())
def print_info(self):
print(' 微波炉的名字是:',self.name,'\n','购买时间是:',self.time)
def bread (self,temp=3):
self.temp = temp
print(" 开始烤面包,时长为:",self.temp,'分钟')
pass
class New_Microwave(Microwave):
'''从Microwave继承的子类'''
def __init__(self,name,light):
super().__init__(name)
self.light = light
def set_light(self,add_light):
self.light=self.light+add_light
print("当前灯光强度为:",self.light)
pass
a=New_Microwave('zhangsan',100)
a.set_light(50)
b = Microwave('zhangsan')
b.set_light(50)
当前灯光强度为: 150
AttributeError: 'Microwave' object has no attribute 'set_light'
Microwave
类和New_Microwave
类,New_Microwave
类继承自Microwave
类,并添加了set_light
方法。New_Microwave
类的对象a
,调用set_light
方法,灯光强度增加 50。Microwave
类的对象b
,尝试调用set_light
方法,会抛出AttributeError
异常,因为Microwave
类没有set_light
方法。import time
class Microwave():
'''微波炉类的文档说明'''
def __init__(self,name):
self.name=name
self.time=time.strftime("%Y-%m-%d %H:%M:%S",time.localtime())
def print_info(self):
print(' 微波炉的名字是:',self.name,'\n','购买时间是:',self.time)
def bread (self,temp=3):
self.temp = temp
print(" 开始烤面包,时长为:",self.temp,'分钟')
pass
class New_Microwave(Microwave):
'''从Microwave继承的子类'''
def __init__(self,name,light):
super().__init__(name)
self.light = light
def print_info(self):
print(' 微波炉的名字是:',self.name,'\n','购买时间是:',self.time,'\n','当前灯光强度时:',self.light)
a=New_Microwave('zhangsan',100)
a.print_info()
微波炉的名字是: zhangsan
购买时间是: 2024-10-12 10:00:00(此处时间根据实际运行时生成)
当前灯光强度时: 100
Microwave
类和New_Microwave
类,New_Microwave
类继承自Microwave
类,并重写了print_info
方法,在打印信息时增加了灯光强度。New_Microwave
类的对象a
,调用重写后的print_info
方法。class Robot():
def __init__(self):
print('我是您的快递小助手')
self.bill = 20230100
self.postage ={'北京':15,'上海':12,'广东':13}
self.q_number = [100,101,104,105]
def send_ex(self):
print('请填写您的寄件信息')
self.addr = input('您的寄件地址:')
self.number = input('您的手机号码:')
self.name = input('您的姓名:')
print('您需要支付',self.postage[ self.addr[0:2] ],'元')
self.bill +=1
print('账单生成中...\n您的寄件单号为:',self.bill)
def collect_ex(self):
self.c_list = int(input('请输入您的取件号:'))
if self.c_list in self.q_number:
print('您的快递已找到,请扫码领取。')
self.q_number.pop()
else:
print('未找到您的快递')
a = Robot()
a.send_ex()
我是您的快递小助手
请填写您的寄件信息
您的寄件地址:北京
您的手机号码:13800138000
您的姓名:张三
您需要支付 15 元
账单生成中...
您的寄件单号为: 20230101
Robot
类,构造函数__init__
初始化一些属性,包括账单号、不同地区的邮费和取件号列表。send_ex
方法用于处理寄件信息,根据输入的地址计算邮费,生成新的账单号。collect_ex
方法用于处理取件信息,根据输入的取件号查找快递。Robot
类的对象a
,调用send_ex
方法处理寄件信息。组织多个文件并相互调用
import time
class Microwave():
'''微波炉类的文档说明'''
def __init__(self,name):
self.name=name
self.time=time.strftime("%Y-%m-%d %H:%M:%S",time.localtime())
def print_info(self):
print(' 微波炉的名字是:',self.name,'\n','购买时间是:',self.time)
def bread (self,temp=3):
self.temp = temp
print(" 开始烤面包,时长为:",self.temp,'分钟')
pass
此代码文件只是定义了一个 Microwave
类,没有可直接运行的代码。若要运行,需要创建类的实例并调用相应的方法。
time
模块,用于获取当前时间。Microwave
类,用于表示微波炉。
__init__
方法:初始化微波炉的名字 name
和购买时间 time
。print_info
方法:打印微波炉的名字和购买时间。bread
方法:开始烤面包,默认时长为 3 分钟。import c
a = c.Microwave('zhangsan')
a.print_info()
微波炉的名字是: zhangsan
购买时间是: (当前时间,格式为 YYYY-MM-DD HH:MM:SS)
c
模块。c.Microwave
类的一个实例 a
,并将微波炉的名字设置为 zhangsan
。a
的 print_info
方法,打印微波炉的名字和购买时间。class Bluetooth():
'''用于连接手机蓝牙'''
def __init__(self, yorn):
self.yorn = yorn
def con(self):
if self.yorn == 'y':
print('开始连接手机蓝牙')
elif self.yorn == 'n':
print('断开手机蓝牙')
else:
print('设置错误')
此代码文件只是定义了一个 Bluetooth
类,没有可直接运行的代码。若要运行,需要创建类的实例并调用相应的方法。
Bluetooth
类,用于处理手机蓝牙的连接和断开。
__init__
方法:初始化一个布尔值 yorn
,表示是否连接蓝牙。con
方法:根据 yorn
的值,打印相应的信息。如果 yorn
为 y
,则开始连接蓝牙;如果为 n
,则断开蓝牙;否则,打印设置错误的信息。import time
import e
class Microwave():
'''微波炉类的文档说明'''
def __init__(self, name):
self.name=name
self.time=time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
def print_info(self):
print(' 微波炉的名字是:',self.name,'\n','购买时间是:', self.time)
def bread (self, temp=3):
self.temp = temp
print(" 开始烤面包,时长为:", self.temp,'分钟')
pass
def con_bluetooth(self, yorn):
bluetooth = e.Bluetooth(yorn)
bluetooth.con()
此代码文件只是定义了一个 Microwave
类,没有可直接运行的代码。若要运行,需要创建类的实例并调用相应的方法。
time
模块和 e
模块。Microwave
类,与 c.py 中的 Microwave
类类似,但增加了一个 con_bluetooth
方法。
__init__
方法:初始化微波炉的名字 name
和购买时间 time
。print_info
方法:打印微波炉的名字和购买时间。bread
方法:开始烤面包,默认时长为 3 分钟。con_bluetooth
方法:创建一个 e.Bluetooth
类的实例,并调用其 con
方法,根据传入的 yorn
值处理蓝牙连接。import f
a = f.Microwave('zhangsan')
a.print_info()
a.con_bluetooth('y')
微波炉的名字是: zhangsan
购买时间是: (当前时间,格式为 YYYY-MM-DD HH:MM:SS)
开始连接手机蓝牙
导入 f
模块。
f.Microwave
类的一个实例 a
,并将微波炉的名字设置为 zhangsan
。a
的 print_info
方法,打印微波炉的名字和购买时间。a
的 con_bluetooth
方法,传入 y
,表示开始连接手机蓝牙。(下一节课:文件操作)