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

  • 相关阅读:
    react-native 调用原生方法
    react-native 生命周期
    查看ubuntu系统信息
    Python之DataFrame将列作为索引
    Python之读取文本文件
    Python 之 直接赋值、Deepcopy、Copy区别
    Python之time与datetime模块
    Python之连接MySQL数据库,执行建表语句
    Python之读取csv文件
    MySQL之count() 函数
  • 原文地址:https://www.cnblogs.com/2018-1025/p/12019670.html
Copyright © 2020-2023  润新知