zoukankan      html  css  js  c++  java
  • python(静态,组合,继承)

    静态属性

    用@property修饰类的行为,把类的行为变成类的属性,有封装的作用

    例子.

    # -*- coding: utf-8 -*-
    class Room:
        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):
            return self.Length*self.Width
    
    room1=Room('102','alex',10,10,3)
    #没有加@property前的调用 # s=room1.cal_area() # print(s) room2=Room('103','alex',10,5,3) # s2=room2.cal_area() # print(s2)
    #加@property后的调用 s1=room1.cal_area print(s1) s2=room2.cal_area print(s2)

    类的方法(在没有把类实例化情况下调用类的方法)

    @classmethod

    # -*- coding: utf-8 -*-
    class Room:
        tag=1
        def __init__(self,name,owner,width,length,heigh):
            self.Name=name
            self.Owner=owner
            self.Width=width
            self.Length=length
            self.Heigh=heigh
    
        def cal_area(self):
            return self.Length*self.Width
    
        @classmethod
        def info(cls):
            print('我是类方法')
            
    Room.info()
    

    静态方法

    @staticmethod

    静态方法只是名义上归属类管理,不能使用类变量与实例变量,是类的工具包

    # -*- coding: utf-8 -*-
    class Room:
        tag=1
        def __init__(self,name,owner,width,length,heigh):
            self.Name=name
            self.Owner=owner
            self.Width=width
            self.Length=length
            self.Heigh=heigh
    
        def cal_area(self):
            return self.Length*self.Width
    
        @classmethod
        def info(cls):
            print('我是类方法')
    
        @staticmethod
        def live(a,b):
            print('%s和%s是住户'%(a,b))
    #类调用
    Room.live('alex','bob')
    #实例调用
    room1=Room('102','alex',10,10,3)
    room1.live('alex','bob')

    总结:@property只与实例绑定(静态属性既可以访问实例属性,又可以访问类属性),@classmethod只与类绑定(类方法只能访问类的属性),@staticmethod类和实例都可以用(类方法既不能类属性,也不能实例属性)

  • 相关阅读:
    Layui数据表格用法
    初识Vue
    使用NPOI导出Excel表
    使用NPOI将Excel表导入到数据库中
    新随笔
    AX2012/D365 SSRS报表开发
    AX2012自定义注释脚本开发
    D365做文件导入导出CSV
    Azure文件上传下载删除(D365可以直接用)
    关于D365/AX2012/C#中的那些json、对象、字符串类型间的转换
  • 原文地址:https://www.cnblogs.com/2018-1025/p/12019670.html
Copyright © 2011-2022 走看看