码迷,mamicode.com
首页 > 编程语言 > 详细

python(静态,组合,继承)

时间:2019-12-11 23:18:04      阅读:100      评论:0      收藏:0      [点我收藏+]

标签:odi   idt   color   继承   property   cme   工具包   组合   不能   

静态属性

用@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(静态,组合,继承)

标签:odi   idt   color   继承   property   cme   工具包   组合   不能   

原文地址:https://www.cnblogs.com/2018-1025/p/12019670.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!