类的组成

mac2022-06-30  34

""" 类的组成: 属性: 类属性/类变量 对象属性/成员属性/成员变量 行为: 对象方法/成员方法 类方法 静态方法 类属于与成员属性: 1.定义位置不同: 类属性定义在类内,方法外 对象属性定义在__init__方法内 2.内存中存储的份数不同 类属性:唯一一份 对象属性:每个对象都有属于自己的一份 3.所有者不同: 类属性: 属于类 对象属性: 属于对象 4.访问方式不同: 类属性: 获取值: 类名.类属性 对象名.类属性 设置值: 类名.类属性 对象属性: 读写: 对象名.属性名 5.生命周期不同 类属性: 程序周期 对象属性: 对象创建时,出生,对象被系统回收时,结束 类方法: 定义: 需要使用@classmethod修饰 有一个必需参数cls 调用: 类名.类方法() 也可以使用对象调 对象.类方法() 静态方法 定义在类内的一个函数 @staticmethod 可以不用有任何参数 调用: 类名.静态方法() 对象.静态方法() """ class Student(object): # 类属性 cls_id = 102 country = 'China' def __init__(self,name,age): self.name = name self.age = age @classmethod def cls_method(cls): print('我是类方法') print(cls) print(cls.cls_id) @staticmethod def static_method(): print('我是静态方法') stu1 = Student('峰哥',40)# Student.__new__().__init__() #类属性的访问 读 print(Student.cls_id) print(stu1.cls_id) # 类属性的访问 写 Student.cls_id = 101 # 为对象动态添加属性 stu1.cls_id = 105 # del stu1 print(Student.cls_id) # 调用类方法 Student.cls_method() # 使用对象调用类方法 stu1.cls_method() # stu1.__class__.cls_method() #调用静态方法 Student.static_method() stu1.static_method()

 

最新回复(0)