python 类属性、静态方法与类方法

1. 类属性

  • 1.1 定义

    • 在类中方法外通过属性名 = 属性值定义的属性
    • 访问方式:
      • 类名.属性名
      • 对象名.属性名
        class Student:
            cls_id = 102
            
        stu = Student()
        print(Student.cls_id)
        print(stu.cls_id)
        
        print("---------")
        
        Student.cls_id = 103
        print(Student.cls_id)
        print(stu.cls_id)
        
        print("---------")
        
        stu.cls_id = 104
        print(Student.cls_id)
        print(stu.cls_id)
        

        运行结果:

        102
        102
        ---------
        103
        103
        ---------
        103
        104
  • 1.2 对象属性与类属性的区别

    • (1)内存中存在数量不同
      • 对象属性:创建了多少个对象,内存中就有多少份
      • 类属性:内存中只存在类中只存在一份,但是对象可读取
    • (2)定义位置不同
      • 对象属性:定义在类内方法内
      • 类属性:定义在类内方法外
    • (3)访问方式不同
      • 对象属性:对象名.属性名
      • 类属性:类名.属性名
        • 读取类属性时,可以通过对象名.属性名
    • (4)生命周期不同
      • 对象属性:创建对象 -> 对象被系统回收
      • 类属性:加载全局命名空间 -> 程序结束
    • (5)所有者不同
      • 对象属性:属于对象
      • 类属性:属于类

2. 静态方法

  • 概念:类中的一个方法
  • 格式:在方法上面添加@staticmethod
  • 参数:可以有参数,也可以没有参数
  • 应用场景:一般用于和类对象以及实例对象无关的代码
  • 使用方式:
    • (1)类名.类方法名
    • (2)对象名.类方法名
  • 使用场景示例:
    • 如:学生管理系统的展示主菜单

3. 类方法

  • 概念:无需实例化就可以通过类直接调用的方法
  • 格式:在方法上面添加@classmethod
  • 参数:方法的第一个参数接收的一定是类本身
    • 方法的参数为cls也可以是其他名称,但是一般默认为cls
    • cls指向类对象(也就是下边示例中Goods)
  • 应用场景:当一个方法中只涉及到静态属性的时候可以使用类方法(类方法用来修改类属性)
  • 使用方式:
    • (1)对象名.类方法名
    • (2)类名.类方法名
  • 使用场景示例:
    • 修改所有商品的折扣
      class Goods():
          discount = 1
          def __init__(self,price,name):
              self.name = name
              self.price = price
          def price_discount(self):
              return self.price * Goods.discount
          @classmethod
          def change_discount(cls,new_discount):
              cls.discount = new_discount
          
          goods = Goods(20, "audi")
          print(goods.price_discount())
          Goods.change_discount(0.5)
          print(goods.price_discount())
      
      运行结果:
      20
      10.0
      

        

       

猜你喜欢

转载自www.cnblogs.com/songdanlee/p/11367584.html