zoukankan      html  css  js  c++  java
  • 面向对象之初始类和对象

    类和对象

    类专业解释为: 类指的是一类具有相同属性和方法的事物的集合。

    对象的专业解释为: 类的实例化为对象

    所以, 需要先定义类, 再通过实例化类得到对象

    Python操作类和对象

    在Python中一切皆是对象

    类的定义

    class Student(object):
        stu_school = 'hnie'
        count = 0
    
        def __init__(self, name, age, gender):
            Student.count += 1
            self.name = name
            self.age = age
            self.gender = gender
    
        def tell_stu_info(self):
            print('学生信息: 名字: %s  年龄: %s  性别: %s' % (
                self.name,
                self.age,
                self.gender
            ))
    
        def set_info(self, name, age, gender):
            self.name = name
            self.age = age
            self.gender = gender

    类是对象相似数据与功能的集合体, 所以类中最常见的是属性与函数的定义, 但是类体中其实是可以包含任意其他代码的。

    在Python中, 类体代码在类的定义阶段就会立即执行, 即会产生类的名称空间

    class Student(object):
        
        print('====>')
    # 运行这段代码的时候, 就会输出"====>", 

    使用内置方法__dict__访问类中的属性和方法

    print(Student.__dict__)
    print(Student.__dict__['stu_school'])  # hnie
    print(Student.__dict__['set_info'])  # <function Student.set_info at 0x7ffc8eebf8c0>

    再调用类产生对象

    stu1_obj = Student()
    stu2_obj = Student()
    stu3_obj = Student()

    但是, 这时候调用类参数的对象为三个空对象, 即没有任何的属性和方法

    print(stu1_obj.__dict__)  # {}
    print(stu2_obj.__dict__)  # {}
    print(stu3_obj.__dict__)  # {}

    可以通过__dict__给对象添加属性

    stu1_obj.__dict__['stu_name'] = 'featherwit'
    stu1_obj.__dict__['stu_age'] = 18
    stu1_obj.__dict__['stu_gender'] = 'male'
    
    print(stu1_obj.__dict__)

    很显然, 这种赋值方式是很复杂的, Python语言是动态的语言, 所以可以通过动态的方式给对象赋值, 这正是Python语言的魅力所在

    stu1_obj.stu_name = 'featherwit'  # stu1_obj.__dict__['stu_name'] = 'featherwit'
    stu1_obj.stu_age = 18  # stu1_obj.__dict__['stu_age'] = 18
    stu1_obj.stu_gender = 'male'  # stu1_obj.__dict__['stu_gender'] = 'male'
    
    print(stu1_obj.__dict__)
  • 相关阅读:
    DS博客作业05--查找
    DS博客作业04--图
    DS博客作业03--树
    DS博客作业02--栈和队列
    C博客作业05-指针
    C语言——数组博客作业
    c语言博客3—函数
    循环结构博客
    c语言博客,顺序与分支结构
    Java面向对象课程设计——购物车
  • 原文地址:https://www.cnblogs.com/featherwit/p/13288777.html
Copyright © 2011-2022 走看看