【Python】通过案例了解(类方法)(实例方法)(静态方法)

一,案例描述

实现GUI界面下学生添加功能的实现

1.  指定 学号,姓名,性别,手机号码,邮箱地址的输入

2.  完成功能的实现并绑定提交按钮

3.  将添加的学生信息写入到文件

4.  通过上述案例分别用 类方法 / 实例方法 / 静态方法  三种方式实现相同的案例

二,类方法的实现

1. 类方法特点:

      1. 类方法前要使用关键字@classmethod

                2. 方法中不能使用self,要使用cls

                3. 类方法能够访问到类变量但是无法访问到实例变量跟实例方法

                4. 调用要通过"类名.方法名"来访问.

                5. 类方法存储在类空间中,没有绑定到对象

2. 代码实现:

 (1)GUI_类

from tkinter import *
import tkinter.ttk as ttk
from tkinter.messagebox import *
from GUI_类方法案例.add_student import Add_student


class Add_Student(Tk):
    #类变量
    file_path = R"C:\Users\Administrator\PycharmProjects\untitled1\GUI_类方法案例\resource\test01.txt"
    input_data = [] #存储输入的每个元素存入列表
    def __init__(self):
        super().__init__()
        self.title("添加学生信息")
        self.geometry("450x430+170+60")
        self.resizable(0, 0)
        self["bg"] = "lightblue"

        #自动添加界面
        self.setUp_UI()

    def setUp_UI(self):
        self.Style01 = ttk.Style()
        self.Style01.configure("TLabel",foreground = "RoyalBlue")
        self.Style01.configure("TButton",font = ("微软雅黑",16,"bold"),foreground = "RoyalBlue")

        self.label01 = ttk.Label(self,text =" 学号: ",font = ("微软雅黑",16,"bold"))
        self.label01.place(x=80,y=80)
        self.var_no = StringVar()
        self.entry01 = ttk.Entry(self,textvariable =self.var_no,font = ("微软雅黑",16,"bold"))
        self.entry01.place(x=150,y=80,width = 120)

        self.label02 = ttk.Label(self,text =" 姓名: ",font = ("微软雅黑",16,"bold"))
        self.label02.place(x=80,y=140)
        self.var_name = StringVar()
        self.entry02 = ttk.Entry(self,textvariable =self.var_name,font = ("微软雅黑",16,"bold"))
        self.entry02.place(x=150,y=140,width = 120)

        self.label03 = ttk.Label(self,text =" 性别: ",font = ("微软雅黑",16,"bold"))
        self.label03.place(x=80,y=200)
        self.var_genter = StringVar()
        self.entry03 = ttk.Entry(self,textvariable =self.var_genter,font = ("微软雅黑",16,"bold"))
        self.entry03.place(x=150,y=200,width = 120)

        self.label04 = ttk.Label(self,text =" 手机号码: ",font = ("微软雅黑",16,"bold"))
        self.label04.place(x=40,y=260)
        self.var_mobile = StringVar()
        self.entry04 = ttk.Entry(self,textvariable =self.var_mobile,font = ("微软雅黑",16,"bold"))
        self.entry04.place(x=150,y=260,width = 240)

        self.label05 = ttk.Label(self,text =" 邮箱地址: ",font = ("微软雅黑",16,"bold"))
        self.label05.place(x=40,y=310)
        self.var_email = StringVar()
        self.entry05 = ttk.Entry(self,textvariable =self.var_email,font = ("微软雅黑",16,"bold"))
        self.entry05.place(x=150,y=310,width = 240)

        self.submit = ttk.Button(self,text = " 提交 ",style = "TButton",command = self.check_input)
        self.submit.place(x=280,y=360,width = 100)

    def check_input(self):
        """
        判断输入是否合规
        :return:
        """
        #1. 获取所有输入的值
        stu_no = self.var_no.get()
        stu_name = self.var_name.get()
        stu_genter = self.var_genter.get()
        stu_mobile = self.var_mobile.get()
        stu_email = self.var_email.get()

        #2. 把输入的值存入类变量list中
        Add_Student.input_data.append(stu_no)
        Add_Student.input_data.append(stu_name)
        Add_Student.input_data.append(stu_genter)
        Add_Student.input_data.append(stu_mobile)
        Add_Student.input_data.append(stu_email)

        #3.实例化Add_student类
        current = Add_student(stu_no,stu_name,stu_genter,stu_mobile,stu_email)

        #4.通过实例化,判断check_all()方法中的每一项输入是否合规
        check_result = Add_student.check_all() #类名.类方法名 (这里的Add_student是类方法案例中的)
        if check_result == 1:
            showinfo("系统消息","学号不符合要求.【要求:95开头的6位数字】")
        elif check_result == 2:
            showinfo("系统消息", "姓名不符合要求.【要求:2-10个汉字】")
        elif check_result == 3:
            showinfo("系统消息", "性别不符合要求.【要求:只能填写男或女】")
        elif check_result == 4:
            showinfo("系统消息", "手机号码不符合要求.【要求:11位数字】")
        elif check_result == 5:
            showinfo("系统消息", "邮箱不符合要求.")
        else:
            #如果符合要求将输入的数据写入到文件.并关闭窗口
            with open(Add_Student.file_path,mode="w",encoding="UTF-8") as fd:
                fd.write("")
            with open(Add_Student.file_path,mode="a",encoding="UTF-8") as fd:
                for item in Add_Student.input_data:
                    temp = item + " "
                    fd.write(temp)
            showinfo("系统消息","文件添加成功!")
            self.close_window()

    def close_window(self):
        self.destroy()
add_stu_gui.py

 (2)add_Student 类

import re

class Add_student():
    """
    类方法特点: 1.类方法前要使用关键字@classmethod
                2. 方法中不能使用self,要使用cls
                3. 类方法能够访问到类变量但是无法访问到实例变量跟实例方法
                4. 调用要通过"类名.方法名"来访问
                5. 类方法存储在类空间中,没有绑定到对象

    """
    no = ""   #类变量
    name = "" #类变量
    genter = ""  #类变量
    mobile = "" #类变量
    email = "" #类变量
    def __init__(self,stu_no:str,stu_name:str,stu_gender:str,stu_mobile:str,stu_email:str):
        Add_student.no = stu_no
        Add_student.name = stu_name
        Add_student.genter = stu_gender
        Add_student.mobile = stu_mobile
        Add_student.email = stu_email

        # 自动运行
        self.check_all()

    @classmethod
    def check_stuno(cls):
        #校验输入的学号是否合规
        partten = re.compile(R"^95\d{4}$") #学号为95开头的6位数字
        match_result = partten.match(cls.no)
        if match_result is None:
            return False
        else:
            return True

    @classmethod
    def check_stuname(cls):
        #校验输入的姓名是否合规
        if len(cls.name.strip())>=2 and len(cls.name.strip())<=10: #判断输入字符串的长度是否在2-10之间(去除空格)
            #如果在范围中再判断输入是否为汉字
            for index in range(len(cls.name.strip())):
                if cls.name[index] < "\u4E00" or cls.name[index] > "\u9FA5": #如果输入不在汉字asc码范围中则不是汉子
                    return False
                if index == len(cls.name.strip()) -1:
                    return True

        else:
            return False

    @classmethod
    def check_stugenter(cls):
        #如果输入包含在 ["男","女"]中则为真,反之为假
        if cls.genter.strip() in ["",""]:
            return True
        else:
            return False

    @classmethod
    def check_stumobile(cls):
        #同上通过正则匹配11位数字,如果输入11数字则为真,反之为假
        partten = re.compile(R"^[1][35789]\d{9}$") #学号为95开头的6位数字
        match_result = partten.match(cls.mobile)
        if match_result is None:
            return False
        else:
            return True

    @classmethod
    def check_stuemail(cls):
        #同上。只是正则匹配的是邮箱地址而已
        partten = re.compile(R"^(\w)+(.\w+)*@(\w)+((.\w+)+)$")  # 学号为95开头的6位数字
        match_result = partten.match(cls.email)
        if match_result is None:
            return False
        else:
            return True

    @classmethod
    def check_all(cls):
        #把情况细化。分别定义学号,姓名,性别,手机号码,邮箱地址为几。便于获取判断
        if not cls.check_stuno():
            return 1
        elif not cls.check_stuname():
            return 2
        elif not cls.check_stugenter():
            return 3
        elif not cls.check_stumobile():
            return 4
        elif not cls.check_stuemail():
            return 5
        else:
            return 0
add_student.py

 (3)start_app类

from GUI_类方法案例.add_stu_gui import Add_Student

if __name__ == "__main__":
    show_gui = Add_Student()
    show_gui.mainloop()
start_app.py

 

三,静态方法的实现

1. 静态方法特点:

                1. 静态方法前要使用关键字@staticmethod
                2. 静态方法中不能使用任何资源(类变量,实例变量都不能使用)(cls,self不能使用)
                3. 调用要通过"类名.方法名"来访问
                4. 静态类方法存储在类空间中
                5. 静态方法相当于一个工具拿来即用

2. 代码实现:

 (1)GUI_类

from tkinter import *
import tkinter.ttk as ttk
from tkinter.messagebox import *
from GUI_静态方法案例.add_student import Add_student


class Add_Student(Tk):
    #类变量
    file_path = R"C:\Users\Administrator\PycharmProjects\untitled1\GUI_静态方法案例\resource\test01.txt"
    input_data = [] #存储输入的每个元素存入列表
    def __init__(self):
        super().__init__()
        self.title("添加学生信息")
        self.geometry("450x430+170+60")
        self.resizable(0, 0)
        self["bg"] = "lightblue"

        #自动添加界面
        self.setUp_UI()

    def setUp_UI(self):
        self.Style01 = ttk.Style()
        self.Style01.configure("TLabel",foreground = "RoyalBlue")
        self.Style01.configure("TButton",font = ("微软雅黑",16,"bold"),foreground = "RoyalBlue")

        self.label01 = ttk.Label(self,text =" 学号: ",font = ("微软雅黑",16,"bold"))
        self.label01.place(x=80,y=80)
        self.var_no = StringVar()
        self.entry01 = ttk.Entry(self,textvariable =self.var_no,font = ("微软雅黑",16,"bold"))
        self.entry01.place(x=150,y=80,width = 120)

        self.label02 = ttk.Label(self,text =" 姓名: ",font = ("微软雅黑",16,"bold"))
        self.label02.place(x=80,y=140)
        self.var_name = StringVar()
        self.entry02 = ttk.Entry(self,textvariable =self.var_name,font = ("微软雅黑",16,"bold"))
        self.entry02.place(x=150,y=140,width = 120)

        self.label03 = ttk.Label(self,text =" 性别: ",font = ("微软雅黑",16,"bold"))
        self.label03.place(x=80,y=200)
        self.var_genter = StringVar()
        self.entry03 = ttk.Entry(self,textvariable =self.var_genter,font = ("微软雅黑",16,"bold"))
        self.entry03.place(x=150,y=200,width = 120)

        self.label04 = ttk.Label(self,text =" 手机号码: ",font = ("微软雅黑",16,"bold"))
        self.label04.place(x=40,y=260)
        self.var_mobile = StringVar()
        self.entry04 = ttk.Entry(self,textvariable =self.var_mobile,font = ("微软雅黑",16,"bold"))
        self.entry04.place(x=150,y=260,width = 240)

        self.label05 = ttk.Label(self,text =" 邮箱地址: ",font = ("微软雅黑",16,"bold"))
        self.label05.place(x=40,y=310)
        self.var_email = StringVar()
        self.entry05 = ttk.Entry(self,textvariable =self.var_email,font = ("微软雅黑",16,"bold"))
        self.entry05.place(x=150,y=310,width = 240)

        self.submit = ttk.Button(self,text = " 提交 ",style = "TButton",command = self.check_input)
        self.submit.place(x=280,y=360,width = 100)

    def check_input(self):
        """
        判断输入是否合规
        :return:
        """
        #1. 获取所有输入的值
        stu_no = self.var_no.get()
        stu_name = self.var_name.get()
        stu_genter = self.var_genter.get()
        stu_mobile = self.var_mobile.get()
        stu_email = self.var_email.get()

        #2. 把输入的值存入类变量list中
        Add_Student.input_data.append(stu_no)
        Add_Student.input_data.append(stu_name)
        Add_Student.input_data.append(stu_genter)
        Add_Student.input_data.append(stu_mobile)
        Add_Student.input_data.append(stu_email)

        if not Add_student.check_stuno(stu_no):
            showinfo("系统消息", "学号不符合要求.【要求:95开头的6位数字】")
        elif not Add_student.check_stuname(stu_name):
            showinfo("系统消息", "姓名不符合要求.【要求:2-10个汉字】")
        elif not Add_student.check_stugenter(stu_genter):
            showinfo("系统消息", "性别不符合要求.【要求:只能填写男或女】")
        elif not Add_student.check_stumobile(stu_mobile):
            showinfo("系统消息", "手机号码不符合要求.【要求:11位数字】")
        elif not Add_student.check_stuemail(stu_email):
            showinfo("系统消息", "邮箱不符合要求.")
        else:
            # 如果符合要求将输入的数据写入到文件.并关闭窗口
            with open(Add_Student.file_path, mode="w", encoding="UTF-8") as fd:
                fd.write("")
            with open(Add_Student.file_path, mode="a", encoding="UTF-8") as fd:
                for item in Add_Student.input_data:
                    temp = item + " "
                    fd.write(temp)
            showinfo("系统消息", "文件添加成功!")
            self.close_window()
    def close_window(self):
        self.destroy()
add_stu_gui.py

 (2)add_Student 类

import re

class Add_student():
    """
    静态方法特点: 1.静态方法前要使用关键字@staticmethod
                2. 静态方法中不能使用任何资源(类变量,实例变量都不能使用)(cls,self不能使用)
                3. 调用要通过"类名.方法名"来访问
                4. 静态类方法存储在类空间中
                5. 静态方法相当于一个工具拿来即用
    """
    @staticmethod
    def check_stuno(no):
        #校验输入的学号是否合规
        partten = re.compile(R"^95\d{4}$") #学号为95开头的6位数字
        match_result = partten.match(no)
        if match_result is None:
            return False
        else:
            return True
    @staticmethod
    def check_stuname(name):
        #校验输入的姓名是否合规
        if len(name.strip())>=2 and len(name.strip())<=10: #判断输入字符串的长度是否在2-10之间(去除空格)
            #如果在范围中再判断输入是否为汉字
            for index in range(len(name.strip())):
                if name[index] < "\u4E00" or name[index] > "\u9FA5": #如果输入不在汉字asc码范围中则不是汉子
                    return False
                if index == len(name.strip()) -1:
                    return True

        else:
            return False

    @staticmethod
    def check_stugenter(genter):
        #如果输入包含在 ["男","女"]中则为真,反之为假
        if genter.strip() in ["",""]:
            return True
        else:
            return False

    @staticmethod
    def check_stumobile(mobile):
        #同上通过正则匹配11位数字,如果输入11数字则为真,反之为假
        partten = re.compile(R"^[1][35789]\d{9}$") #学号为95开头的6位数字
        match_result = partten.match(mobile)
        if match_result is None:
            return False
        else:
            return True

    @staticmethod
    def check_stuemail(email):
        #同上。只是正则匹配的是邮箱地址而已
        partten = re.compile(R"^(\w)+(.\w+)*@(\w)+((.\w+)+)$")  # 学号为95开头的6位数字
        match_result = partten.match(email)
        if match_result is None:
            return False
        else:
            return True
add_student.py

 (3)start_app 类

from GUI_静态方法案例.add_stu_gui import Add_Student

if __name__ == "__main__":
    show_gui = Add_Student()
    show_gui.mainloop()
start_app.py

 

四,实例方法的实现

1. 实例方法特点:

                1. 实例方法创建关键字使用的是self
                2. 调用通过实例化过后类名.方法名来访问,也可以通过对象名.方法名来访问.(推荐: 对象名.方法名)
                3. 实例方法每实例化一次band一次地址给对象(对象只是通过地址来访问实例方法)

                4. 实例变量不同.每实例化一次开辟一块内存空间给对象

2. 代码实现:

 (1)GUI_类

from tkinter import *
import tkinter.ttk as ttk
from tkinter.messagebox import *
from GUI_实例方法案例.add_student import Add_student


class Add_Student(Tk):
    #类变量
    file_path = R"C:\Users\Administrator\PycharmProjects\untitled1\GUI_实例方法案例\resource\test01.txt"
    input_data = [] #存储输入的每个元素存入列表
    def __init__(self):
        super().__init__()
        self.title("添加学生信息")
        self.geometry("450x430+170+60")
        self.resizable(0, 0)
        self["bg"] = "lightblue"

        #自动添加界面
        self.setUp_UI()

    def setUp_UI(self):
        self.Style01 = ttk.Style()
        self.Style01.configure("TLabel",foreground = "RoyalBlue")
        self.Style01.configure("TButton",font = ("微软雅黑",16,"bold"),foreground = "RoyalBlue")

        self.label01 = ttk.Label(self,text =" 学号: ",font = ("微软雅黑",16,"bold"))
        self.label01.place(x=80,y=80)
        self.var_no = StringVar()
        self.entry01 = ttk.Entry(self,textvariable =self.var_no,font = ("微软雅黑",16,"bold"))
        self.entry01.place(x=150,y=80,width = 120)

        self.label02 = ttk.Label(self,text =" 姓名: ",font = ("微软雅黑",16,"bold"))
        self.label02.place(x=80,y=140)
        self.var_name = StringVar()
        self.entry02 = ttk.Entry(self,textvariable =self.var_name,font = ("微软雅黑",16,"bold"))
        self.entry02.place(x=150,y=140,width = 120)

        self.label03 = ttk.Label(self,text =" 性别: ",font = ("微软雅黑",16,"bold"))
        self.label03.place(x=80,y=200)
        self.var_genter = StringVar()
        self.entry03 = ttk.Entry(self,textvariable =self.var_genter,font = ("微软雅黑",16,"bold"))
        self.entry03.place(x=150,y=200,width = 120)

        self.label04 = ttk.Label(self,text =" 手机号码: ",font = ("微软雅黑",16,"bold"))
        self.label04.place(x=40,y=260)
        self.var_mobile = StringVar()
        self.entry04 = ttk.Entry(self,textvariable =self.var_mobile,font = ("微软雅黑",16,"bold"))
        self.entry04.place(x=150,y=260,width = 240)

        self.label05 = ttk.Label(self,text =" 邮箱地址: ",font = ("微软雅黑",16,"bold"))
        self.label05.place(x=40,y=310)
        self.var_email = StringVar()
        self.entry05 = ttk.Entry(self,textvariable =self.var_email,font = ("微软雅黑",16,"bold"))
        self.entry05.place(x=150,y=310,width = 240)

        self.submit = ttk.Button(self,text = " 提交 ",style = "TButton",command = self.check_input)
        self.submit.place(x=280,y=360,width = 100)

    def check_input(self):
        """
        判断输入是否合规
        :return:
        """
        #1. 获取所有输入的值
        stu_no = self.var_no.get()
        stu_name = self.var_name.get()
        stu_genter = self.var_genter.get()
        stu_mobile = self.var_mobile.get()
        stu_email = self.var_email.get()

        #2. 把输入的值存入类变量list中
        Add_Student.input_data.append(stu_no)
        Add_Student.input_data.append(stu_name)
        Add_Student.input_data.append(stu_genter)
        Add_Student.input_data.append(stu_mobile)
        Add_Student.input_data.append(stu_email)

        #3.实例化Add_student类
        current = Add_student(stu_no,stu_name,stu_genter,stu_mobile,stu_email)

        #4.通过实例化,判断check_all()方法中的每一项输入是否合规
        check_result = current.check_all()
        if check_result == 1:
            showinfo("系统消息","学号不符合要求.【要求:95开头的6位数字】")
        elif check_result == 2:
            showinfo("系统消息", "姓名不符合要求.【要求:2-10个汉字】")
        elif check_result == 3:
            showinfo("系统消息", "性别不符合要求.【要求:只能填写男或女】")
        elif check_result == 4:
            showinfo("系统消息", "手机号码不符合要求.【要求:11位数字】")
        elif check_result == 5:
            showinfo("系统消息", "邮箱不符合要求.")
        else:
            #如果符合要求将输入的数据写入到文件.并关闭窗口
            with open(Add_Student.file_path,mode="w",encoding="UTF-8") as fd:
                fd.write("")
            with open(Add_Student.file_path,mode="a",encoding="UTF-8") as fd:
                for item in Add_Student.input_data:
                    temp = item + " "
                    fd.write(temp)
            showinfo("系统消息","文件添加成功!")
            self.close_window()

    def close_window(self):
        self.destroy()
add_stu_gui.py

 (2)add_Student 类

import re

class Add_student():
    def __init__(self,stu_no:str,stu_name:str,stu_gender:str,stu_mobile:str,stu_email:str):
        self.no = stu_no
        self.name = stu_name
        self.genter = stu_gender
        self.mobile = stu_mobile
        self.email = stu_email

        # 自动运行
        self.check_all()

    def check_stuno(self):
        #校验输入的学号是否合规
        partten = re.compile(R"^95\d{4}$") #学号为95开头的6位数字
        match_result = partten.match(self.no)
        if match_result is None:
            return False
        else:
            return True

    def check_stuname(self):
        #校验输入的姓名是否合规
        if len(self.name.strip())>=2 and len(self.name.strip())<=10: #判断输入字符串的长度是否在2-10之间(去除空格)
            #如果在范围中再判断输入是否为汉字
            for index in range(len(self.name.strip())):
                if self.name[index] < "\u4E00" or self.name[index] > "\u9FA5": #如果输入不在汉字asc码范围中则不是汉子
                    return False
                if index == len(self.name.strip()) -1:
                    return True

        else:
            return False

    def check_stugenter(self):
        #如果输入包含在 ["男","女"]中则为真,反之为假
        if self.genter.strip() in ["",""]:
            return True
        else:
            return False

    def check_stumobile(self):
        #同上通过正则匹配11位数字,如果输入11数字则为真,反之为假
        partten = re.compile(R"^[1][35789]\d{9}$") #学号为95开头的6位数字
        match_result = partten.match(self.mobile)
        if match_result is None:
            return False
        else:
            return True

    def check_stuemail(self):
        #同上。只是正则匹配的是邮箱地址而已
        partten = re.compile(R"^(\w)+(.\w+)*@(\w)+((.\w+)+)$")  # 学号为95开头的6位数字
        match_result = partten.match(self.email)
        if match_result is None:
            return False
        else:
            return True

    def check_all(self):
        #把情况细化。分别定义学号,姓名,性别,手机号码,邮箱地址为几。便于获取判断
        if not self.check_stuno():
            return 1
        elif not self.check_stuname():
            return 2
        elif not self.check_stugenter():
            return 3
        elif not self.check_stumobile():
            return 4
        elif not self.check_stuemail():
            return 5
        else:
            return 0
add_student.py

 (3)start_app 类

from GUI_实例方法案例.add_stu_gui import Add_Student

if __name__ == "__main__":
    show_gui = Add_Student()
    show_gui.mainloop()
start_app.py

 

友情提醒:不管使用什么方法都可以实现以上的功能。但是对于不同的方法的了解,可以更加清晰的认识代码在内存中如何开辟空间又如何实现功能的。

                 另外import包的时候不要导错包

 

你可能感兴趣的:(【Python】通过案例了解(类方法)(实例方法)(静态方法))