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类和实例都可以用(类方法既不能类属性,也不能实例属性)

  • 相关阅读:
    Python教程:从零到大师
    Hive 安装 & Mysql 安装
    Hive基本原理及配置Mysql作为Hive的默认数据库
    分布式存储系统-HDFS
    centos 6.4-linux环境配置,安装hadoop-1.1.2(hadoop伪分布环境配置)
    VirtualBox安装Centos出现E_FAIL (0x80004005)的解决方法
    Hadoop 中HDFS、MapReduce体系结构
    探索性测试及基本用例
    软件测试相关术语(测试策略 && 测试方案 ....)
    高效学习的疑问与思路[软技能]
  • 原文地址:https://www.cnblogs.com/2018-1025/p/12019670.html
Copyright © 2011-2022 走看看