python @property的用法及含义全面解析

yipeiwu_com5年前Python基础

在接触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就起到这种作用(类似于java中的private)

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)

此时就可以对“属性”进行赋值操作,同样的方法还del,用处是删除属性,写法如下,具体实现不在赘述。

@height.deleter
def height(self):
    del self.true_height

总结一下@property提供了可读可写可删除的操作,如果像只读效果,就只需要定义@property就可以,不定义代表禁止其他操作。

以上这篇python @property的用法及含义全面解析就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

Python 字典(Dictionary)操作详解

Python字典是另一种可变容器模型,且可存储任意类型对象,如字符串、数字、元组等其他容器模型。 一、创建字典 字典由键和对应值成对组成。字典也被称作关联数组或哈希表。基本语法如下:...

python模块之time模块(实例讲解)

python模块之time模块(实例讲解)

time 表示时间的三种形式 时间戳(timestamp) :通常来说,时间戳表示的是从1970年1月1日00:00:00开始按秒计算的偏移量。我们运行“type(time.time()...

Python求均值,方差,标准差的实例

如下所示: import numpy as np arr = [1,2,3,4,5,6] #求均值 arr_mean = np.mean(arr) #求方差 arr_var = n...

利用python微信库itchat实现微信自动回复功能

前言 在论坛上看到了用Python登录微信并实现自动签到,才了解到一个新的Python库: itchat 利用Python 微信库itchat,可以实现自动回复等多种功能,好玩到根本停不...

python去掉行尾的换行符方法

如下所示: mystring.strip().replace(' ', '').replace('\n', '').replace('\t', '').replace('\r', '')...