(纯新手练习五)python基础代码,我手把手带你敲(类与对象,实例,构造函数__init__初始化对象属性,继承,方法重写,类的文档字符串,模块化)

目录

1.基本理论简述

类与对象

构造函数(Constructor)

继承(Inheritance)

方法重写(Method Overriding)

四者关系总结

类的文档字符串(Docstring)

2.练习开始

3.代码模块化练习


(纯新手练习五)python基础代码,我手把手带你敲(类与对象,实例,构造函数__init__初始化对象属性,继承,方法重写,类的文档字符串,模块化)

(下一节课:文件操作)

基本理论简述

类与对象

类(Class)

  • 是创建对象的蓝图或模板,定义了一组属性和方法。
  • 类似于 “类型” 的抽象概念(如 “人类”)。

对象(Object)

  • 是类的具体实例,具有类定义的属性和方法。
  • 类似于 “个体”(如 “张三” 是 “人类” 的一个实例)。

示例

class Dog:  # 类定义
    def bark(self):  # 方法
        print("汪汪")

my_dog = Dog()  # 创建对象(实例化)
my_dog.bark()   # 调用对象的方法

构造函数(Constructor)

定义

  • 类中的特殊方法,用于初始化对象的属性。
  • Python 中使用__init__方法作为构造函数。

作用

  • 在创建对象时自动调用,设置初始状态。

示例

class Dog:
    def __init__(self, name, age):  # 构造函数
        self.name = name  # 实例属性
        self.age = age

my_dog = Dog("小白", 3)  # 初始化属性
print(my_dog.name)  # 输出:小白

继承(Inheritance)

定义

  • 子类自动获取父类的属性和方法的机制。

作用

  • 实现代码复用,建立类之间的层次关系。

示例

class Animal:  # 父类
    def eat(self):
        print("吃东西")

class Dog(Animal):  # 子类继承父类
    def bark(self):
        print("汪汪")

my_dog = Dog()
my_dog.eat()  # 继承自父类的方法
my_dog.bark() # 子类自己的方法

方法重写(Method Overriding)

定义

  • 子类重新实现父类中已有的方法,覆盖父类的行为。

作用

  • 让子类根据自身需求修改或扩展父类方法。

示例

class Animal:
    def speak(self):
        print("动物发声")

class Dog(Animal):
    def speak(self):  # 重写父类方法
        print("汪汪")

my_dog = Dog()
my_dog.speak()  # 输出:汪汪(调用子类重写后的方法)

四者关系总结

  1. 定义了对象的结构和行为。
  2. 构造函数在创建对象时初始化属性。
  3. 继承允许子类复用父类的代码。
  4. 方法重写使子类能修改父类的行为,实现个性化定制。

类的文档字符串(Docstring)

定义:类定义内部的第一个字符串,用于描述类的功能和用法。
作用:提供代码文档,可通过__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__)  # 输出方法的文档字符串
# 输出:
# """计算两个数的和"""

规范

  • 使用三引号(""")包裹多行文档。
  • 首行简要描述功能,后续段落详细说明。
  • 可包含参数、返回值、异常等说明(如 NumPy 风格、Google 风格)。

练习开始

程序 1

代码
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__方法是类的构造函数,用于初始化对象的属性,包括nametimetime是当前时间。
  • print_info方法用于打印微波炉的名字和购买时间。
  • bread方法用于模拟烤面包的操作,默认烤面包时长为 3 分钟。
  • 创建了一个Microwave类的对象a,并调用了print_infobread方法。

程序 2

代码
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_infobread方法。
  • 创建了Microwave类的对象a,调用bread方法开始烤面包,最后打印烤面包的时长。

程序 3

代码
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__方法,开始烤面包。
  • 最后打印对象的nametimetemp属性。

程序 4

代码
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后,修改了对象的nametime属性,最后打印修改后的属性值。

程序 5

代码
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__属性打印类的文档说明。

程序 6

代码
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方法,该方法继承自父类。

程序 7

代码
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属性。

程序 8

代码
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方法。

程序 9

代码
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方法。

程序 10

代码
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方法处理寄件信息。

代码模块化练习

组织多个文件并相互调用

代码文件 c.py

代码
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 分钟。

代码文件 d.py

代码
import c  
a = c.Microwave('zhangsan')
a.print_info()
运行结果
 微波炉的名字是: zhangsan 
 购买时间是: (当前时间,格式为 YYYY-MM-DD HH:MM:SS)
代码解析
  • 导入 c 模块。
  • 创建 c.Microwave 类的一个实例 a,并将微波炉的名字设置为 zhangsan
  • 调用 a 的 print_info 方法,打印微波炉的名字和购买时间。

代码文件 e.py

代码
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,则断开蓝牙;否则,打印设置错误的信息。

代码文件 f.py

代码
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 值处理蓝牙连接。

代码文件 g.py

代码
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,表示开始连接手机蓝牙。

(下一节课:文件操作)

你可能感兴趣的:(python,开发语言)