• Python进阶编程 面向对象


    一.面向对象

    1.1面向对象的基本格式

    class 类名:
        def 方法名(self):
            print(123)
            return 123
        def 方法名(self):
            print(123)
            return 123
    ###调用类中的方法###
    #1.实例化一个对象
    obj=类名()
    #2.通过对象调用方法
    result=obj.方法名()
    

    类名的角度调用类中的属性.

    1. 查看类中的所有的内容.  类名.__dict__只用于获取类中的全部.
    # print(Student.__dict__)
    # print(Student.__dict__['daily'])
    

    万能的 .点.

     print(Student.daily)  # 查
     Student.cloth = '校服'  # 增
     print(Student.__dict__)
     Student.examination = '不考试!'  # 改
     print(Student.examination)
     del Student.daily  # 删
     print(Student.__dict__)
    

    一般类中的属性都是通过类名.的方式去操控的.

    实例化对象发生的三件事

      1. 在内存中创建一个对象空间.*
      1. 自动执行__init__方法,并且将对象空间传给self参数.*
      1. 执行__init__方法里面的代码,给对象空间封装其属性.*
    class Student:
        """
        此类是构建学生类
        """
    
        daily = '学习'
        examination = '考试'
    
        def __init__(self,n,a,h):
    
            # self.n = '小黑'
            # self.sex = '随便'
            self.name = n
            self.age = a
            self.hobby = h
    
        def work(self,c):
            # self.color = '绿色'
            self.color = c
            print(f'{self.name}每天要上课')
    
        def homework(self):
            # 利用self 对象空间,为所欲为
            print('家庭作业')
    

    对象操作对象里面的属性.

     对象查看全部属性
    print(obj.__dict__)
    对象可以操作对象空间的属性  万能的点
    obj.age = '29'  # 增
    del obj.n  # 删
    obj.sex = '女'# 改
    print(obj.n)  # 查
    
    

    对象查看类中的属性.

    对象查看类中的属性.
    print(mc_sq.daily)
    对象调用类中的方法
    liye.work('绿油油')
    print(liye.__dict__)
    

    从空间角度研究类

    **对象如果查询一个属性: 对象空间 ----> 类空间 ----> 父类空间 **

    类查询一个属性: 类空间 ----> 父类空间

    对象与对象之间原则上互相独立(除去组合这种特殊的关系之外).

  • 相关阅读:
    JZOJ 3845. 简单题(simple)
    JZOJ 3844. 统计损失(count)
    JZOJ 3843. 寻找羔羊(agnus)
    JZOJ 3833. 平坦的折线
    JZOJ 1956. 矩形
    JZOJ 3832. 在哪里建酿酒厂
    mysql 语法一 :case when详解
    阿里云推荐码
    redis配置文件详解(转)
    压力测试工具 webbench总结
  • 原文地址:https://www.cnblogs.com/llwwhh/p/11318018.html
Copyright © 2020-2023  润新知