zoukankan      html  css  js  c++  java
  • 静态属性、类方法、静态方法

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

    1. 静态属性:在函数前加@property,将函数逻辑”封装“成数据属性,外部直接调用函数名,如同调用属性一样。这个函数是可以调用类和实例的属性的,
        静态属性的作用是把类的方法隐藏起来(可以把背后的逻辑隐藏起来),让用户感觉是在调用属性,而不是方法;

    class Room:
        res = "alex"
        def __init__(self,name,owner,width,length,heigh):
            self.name = name
            self.owner = owner
            self.width = width
            self.length = length
            self.heigh = heigh
        @property #即可调用实例属性也可调用类属性
        def cal_area(self):
            print(p1.width * p1.length,Room.res)
    p1 = Room("四合院","alex",10,10,20)
    p1.cal_area
    #print(Room.__dict__)#'cal_area': <property object at 0x00000219606DD4F8>

    2. 类方法:在类的方法前添加@classmethod,不需要实例化,直接调用类的该方法,可以访问类的数据属性,但是不可以访问对象的数据属性。
         @classmethod类方法是通过类里面的函数调用类本身的属性(不跟实例捆绑只和类捆绑,不用实例化)
         类方法的定义只是为了类去调用

    class Room:
        res = "alex"
        def __init__(self,name,owner,width,length,heigh):
            self.name = name
            self.owner = owner
            self.width = width
            self.length = length
            self.heigh = heigh
        @classmethod #类方法只能调用类属性,不能调用实例属性
        def cal_area(cls):
            print(Room.res) #调用类的数据属性
    #p1 = Room("四合院","alex",10,10,20) #不需要实例化
    Room.cal_area()

    3. 静态方法:在类的方法前加@staticmethod,该方法只是名义上的归属类管理,实例和类的属性均不可以访问,仅仅是类的工具包。
          可以理解为静态方法只是借用类的大树下的一个独立函数

    class Room:
        res = "alex"
        def __init__(self,name,owner,width,length,heigh):
            self.name = name
            self.owner = owner
            self.width = width
            self.length = length
            self.heigh = heigh
        @staticmethod #类属性和实例属性都不可以调用
        def cal_area(x,y):
            print(x,y,)
    p1 = Room("四合院","alex",10,10,20) #不需要实例化
    Room.cal_area(1,2)
    p1.cal_area(1,2)
  • 相关阅读:
    存储过程
    pl/sql锁
    事务处理
    记录类型(学习笔记)
    ExecutorException: A query was run and no Result Maps were found for the Mapped Statement ''. It's likely that neither a Result Type nor a Result Map was specified.
    element中的el-form踩的坑
    关于location.href家族的区别和用法
    ajax的路径跳转
    使用thymeleaf模板引擎时的路径问题
    关于mybatis的传多个参数的问题
  • 原文地址:https://www.cnblogs.com/NumerOne/p/11465066.html
Copyright © 2011-2022 走看看