第36讲类(中)(和猫妹学Python)
小朋友们好,大朋友们好!
我们今天继续学习类,今天学习的内容有:
属性(property)
创建用于计算的属性(property)
为属性(property)添加安全保护机制
属性(property)
本节的属性(property)不同于之前学的类属性和实例属性。
类属性和实例属性:返回所存储的值。
属性(property):访问方法计算后所得的值。
创建用于计算的属性(property)
使用@property把方法转换为属性(property),返回计算的结果,这种用法也称为装饰器。
语法如下:
@property
def methodname(self):
block
@property:关键字,含义是将下面方法变为属性(property)
block:方法实现,一般会有一个return语句
猫妹的测试代码36.2.py class Rect: def __init__(self,width,height):#构造方法 self.width = width #矩形宽度 self.height = height #矩形高度 @property def area(self): return self.width *self.height rect1=Rect(3,4)#创建类的实例 print("面积是:",rect1.area)#输出面积
为属性(property)添加安全保护机制
当类的成员变量,需要可以读取但不可以修改时,可以借助于属性(property)实现。
读取属性(property),但是不可以修改其值。
猫妹的测试代码36.3.1py class TVshow: def __init__(self,show): self.__show = show @property def show(self): return self.__show tvshow = TVshow("正在播放《战狼2》") print("默认:",tvshow.show) #tvshow.show = "长津湖"#不可以直接修改
为属性(property)添加过滤器,可以修改属性(property)。
猫妹的测试代码36.3.2py class TVshow: list_film = ["战狼2","红海行动","水浒传","葫芦娃"] def __init__(self,show): self.__show = show @property def show(self): return self.__show @show.setter def show(self,value):#为属性添加过滤器 if value in TVshow.list_film: self.__show = value else: self.__show = "您点播的电影不存在" tvshow = TVshow("战狼2") print(tvshow.show) tvshow.show = "葫芦娃" print(tvshow.show) tvshow.show = "机器猫" print(tvshow.show)
好了,今天的学习就到这里!
我们下次见!