@property

python的@property是python的一种装饰器,是用来修饰方法的。

作用:

我们可以使用@property装饰器来创建只读属性,@property装饰器会将方法转换为相同名称的只读属性,可以与所定义的属性配合使用,这样可以防止属性被修改。

使用场景:

1.修饰方法,是方法可以像属性一样访问

class DataSet(object):
  @property
  def method_with_property(self): ##含有@property
      return 15
  def method_without_property(self): ##不含@property
      return 15

l = DataSet()
print(l.method_with_property) # 加了@property后,可以用调用属性的形式来调用方法,后面不需要加()。
print(l.method_without_property())  #没有加@property , 必须使用正常的调用方法的形式,即在后面加()

2.与所定义的属性配合使用,这样可以防止属性被修改。

在接触python时最开始接触的代码,取长方形的长和宽,定义一个长方形类,然后设置长方形的长宽属性,通过实例化的方式调用长和宽,像如下代码一样。

class Rectangle(object):
    def __init__(self):
        self.width =10
        self.height=20
r=Rectangle()
print(r.width,r.height)

此时输出结果为10 20 
但是这样在实际使用中会产生一个严重的问题,__init__ 中定义的属性是可变的,换句话说,是使用一个系统的所有开发人员在知道属性名的情况下,可以进行随意的更改(尽管可能是在无意识的情况下),但这很容易造成严重的后果。

class Rectangle(object):
    def __init__(self):
        self.width =10
        self.height=20
r=Rectangle()
print(r.width,r.height)
r.width=1.0
print(r.width,r.height)

以上代码结果会输出宽1.0,可能是开发人员不小心点了一个小数点上去,但是系统的数据会错误,并且在一些情况下很难排查。 
这是生产中很不情愿遇到的情况,这时候就考虑能不能将width属性设置为私有的,其他人不能随意更改的属性,如果想要更改只能依照我的方法来修改,@property就起到这种作用

class Rectangle(object):
    @property
    def width(self):
        #变量名不与方法名重复,改为true_width,下同
        return self.true_width

    @property
    def height(self):
        return self.true_height
s = Rectangle()
#与方法名一致
s.width = 1024
s.height = 768
print(s.width,s.height)

(@property使方法像属性一样调用,就像是一种特殊的属性) 
此时,如果在外部想要给width重新直接赋值就会报AttributeError: can’t set attribute的错误,这样就保证的属性的安全性。

同样为了解决对属性的操作,提供了封装方法的方式进行属性的修改

class Rectangle(object):
    @property
    def width(self):
        # 变量名不与方法名重复,改为true_width,下同
        return self.true_width
    @width.setter
    def width(self, input_width):
        self.true_width = input_width
    @property
    def height(self):
        return self.true_height
    @height.setter
    #与property定义的方法名要一致
    def height(self, input_height):
        self.true_height = input_height
s = Rectangle()
# 与方法名一致
s.width = 1024
s.height = 768
print(s.width,s.height)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值