• 第七天(2):面向对象编程


    面向对象

    1、步骤

    OOA面向对象分析

    OOD面向对象设计

    OOP面向对象编程

    def search_book(title):
        print('搜索包含书关键词{}的图书'.format(title))
    book = {
        'title':'Python入门',
        'price':39.00,
        'author':"Peter",
        'search_book':search_book
    }
    print(book['title'])
    print(book.get('price', 0.0))
    book.get('search_book')('Python')  #在这个.get方法后面记得加上传递参数的值,因为调用的search_book函数这个需要输入参数
    
    Python入门
    39.0
    搜索包含书关键词Python的图书
    

    2、实现

    分析对象特征行为

    写类描述对象模板

    实例化,模拟过程

    import datetime
    class Book:  #长的命名就连在一起,在第二个单词开头大写,不在词中间添加下划线
        def __init__(self,title,
                     price=0.0,
                     author='',
                     publisher=None,
                     pubdate=datetime.date.today()):  #这种有一两个下划线开头结尾的叫预定义
            self.title = title  #定义了对象的特征
            self.price = price
            self.author = author
            self.publisher = publisher
            self.pubdate = pubdate
        def __repr__(self):
            return '<图书 {} at 0x{}>'.format(self.title,id(self))
        def print_info(self):
            print('当前这本书的信息如下:')
            print('标题:{}'.format(self.title))
            print('定价:{}'.format(self.price))
            print('作者:{}'.format(self.author))
            print('出版社:{}'.format(self.publisher))
            print('出版时间:{}'.format(self.pubdate))      
    book1 = Book('C#精典',29.9,'Tom','优品课堂',datetime.date(2016,3,1))
    book1.print_info()
    
    当前这本书的信息如下:
    标题:C#精典
    定价:29.9
    作者:Tom
    出版社:优品课堂
    出版时间:2016-03-01
    
    book = Book('ASP.NET')
    book.title
    book.pubdate
    book.price
    book
    
    'ASP.NET'
    datetime.date(2019, 9, 4)
    0.0
    <图书 ASP.NET at 0x1935503916224>
    

    3、特征

    • 面向过程编程: 数据和处理数据的函数是彼此独立的,我们需要先将数据处理成函数能接受的格式,再调用相关函数处理
    • 面向对象编程: 数据和处理数据的函数都在一个 类 中(Class),通过初始化 实例 (Instance)传递数据,通过实例调用对象方法或者说叫实例方法

    封装

    class Book: # 这里就是初始化你将要创建的实例的属性
        count = 0
        def __init__(self,title,price=0.0,author=None):#初始化执行
            self.title = title
            self.price = price
            self.author = author
            Book.count += 1 #写self跟实例有关,不写跟类有关
        下面是定义你将要创建的实例所拥有的技能
        def __del__(self): #删除对象执行
            Book.count -= 1
        def __repr__(self): #输入对象名显示内容(程序员用)
            return '<图书:{} at 0x{}>'.format(self.title,id(self))
        def __str__(self): #print(对象名)显示内容(用户用)
            return '[图书: {},定价:{}]'.format(self.title,self.price)
        def print_info(self):#在这个类函数里面加self的都是实例函数,与实例有关
            print(self.title,self.price,self.author)
        def static_method(cls):
            print('类函数(对应类,但通过参数可访问实例')
        def static_method(): #静态函数(逻辑上与实例无关),无self、cls参数
            print('静态函数,逻辑上与实例无关')
    if __name__ == '__main__': #当.py文件被直接运行时,if __name__ == '__main__'之下的代码块将被运行;当.py文件以模块形式被导入时,if __name__ == '__main__'之下的代码块不被运行。
        book = Book('Python经典',price= 29.0,author='Tom')
        book2 = Book('Flask')
        book3 = Book('ASP.net')
        book = static_method() #前面不加self,所以后面与实例无关,不用传入实例
    
    import datetime
    class Student:
        def __init__(self,name,birthday): #本来可以直接设置age年龄这个属性,但是由于人的年龄是不断变化的
            self.name = name
            self.birthday = birthday
        @property #类属性声明
        def age(self):
            return datetime.date.today().year - self.birthday.year
        @age.setter #类属性设置声明,格式:@属性名.setter
        def age(self,value):
            raise AttributeError('禁止赋值年龄!')
        @age.deleter # 类属性删除声明,格式:@属性名.deleter
        def age(self):
            raise AttributeError('年龄不能删除!')
    if __name__ == '__main__':
        s = Student('Tom', datetime.date(1992,3,1))
        print(s.birthday)
        print(s.age)
        s.birthday = datetime.date(1982,8,2)
        # del(s.name) #可以使用这种方法来删除属性
        # print(s.name)
        del(s.age) #年龄是另外赋值的,此属性已设置不能删除
        print(s.age)
    

    继承

    import datetime
    class Student:
        def __init__(self,name,birthday): #本来可以直接设置age年龄这个属性,但是由于人的年龄是不断变化的
            self.name = name
            self.birthday = birthday
        @property #类属性声明
        def age(self):
            return datetime.date.today().year - self.birthday.year
        @age.setter #类属性设置声明,格式:@属性名.setter
        def age(self,value):
            raise AttributeError('禁止赋值年龄!')
        @age.deleter # 类属性删除声明,格式:@属性名.deleter
        def age(self):
            raise AttributeError('年龄不能删除!')
    if __name__ == '__main__':
        s = Student('Tom', datetime.date(1992,3,1))
        print(s.birthday)
        print(s.age)
        s.birthday = datetime.date(1982,8,2)
        # del(s.name) #可以使用这种方法来删除属性
        # print(s.name)
        del(s.age) #年龄是另外赋值的,此属性已不能删除
        print(s.age)
    
    import datetime
    class Department:
        def __init__(self,department,phone,manager):
            self.department = department
            self.phone = phone
            self.manager = manager
        def __repr__(self):
            return '<部门: {}>'.format(self.department)
    class Employee:
        def __init__(self,department:Department,name,birthday,salary):
            self.department = department
            self.name = name
            self.birthday = birthday
            self.salary = salary
        @property
        def age(self):
            return datetime.date.today().year - self.birthday.year
        def give_raise(self,percent,bonus=.0):
            self.salary = self.salary * (1 + percent + bonus)
        def __repr__(self):
            return '<员工:{}>'.format(self.name)
        def working(self):
            print('员工:{}, 在工作...'.format(self.name))
    class Programer(Employee): #继承上面的基类
        def __init__(self,department,name,birthday,salary,specialty,project):
            super().__init__(department,name,birthday,salary) #使用基类的初始化,然后这个类就不需再初始化了
            self.specialty = specialty
            self.project = project
        def working(self):  #重载,体现多态的特征
            print('程序员: {}在开发项目:...'.format(self.name,self.project))
    class HR(Employee):
        def __init__(self,department,name,birthday,salary,qualification_level=1):
            Employee.__init__(self,department,name,birthday,salary)
            self.qualification_level = qualification_level
        def working(self):
            print('人事:{}正在面试新员工...'.format(self.name))
    if __name__ == '__main__':
        # p = Programer('技术部','Peter',datetime.date(1985,3,1),8000.0,'Python','CRM')
        # print(p)
        # print(p.department)
        # print(p.salary)
        # p.give_raise(.2,.1)
        # print(p.salary)
        # p.working()
        # print(p.age)
        # hr = HR('人事部','Marry',datetime.date(1992,4,4),6000,qualification_level=3)
        # hr.give_raise(.1)
        # print(hr.salary)
        # hr.working()
        dep = Department('技术部','010-23243','张三')
        p = Programer(dep,'Peter',datetime.date(1990,2,3),23233,'Python,Flask','XMall')
        p.give_raise(.2,.1)
        print(p.salary)
        print(p.department.department)
    

    多态

    • 多态,同一类型的不同实例
  • 相关阅读:
    Python MongoDB使用介绍
    算法网站
    无限级树状图css实现
    无限级别分类嵌套格式抓取
    无限级别分类
    计算多维数组到底是几维的
    获取无限级别分类
    mysql 重启
    radio 控制器function用法
    php-fpm 重启 nginx单独配置 重启
  • 原文地址:https://www.cnblogs.com/linyk/p/11462222.html
Copyright © 2020-2023  润新知