python @property的介绍与使用

python的@property是python的一种装饰器,是用来修饰方法的。
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 , 必须使用正常的调用方法的形式,即在后面加()

使用 @property 修饰了 method_with_property() 方法,这样就使得该方法变成了 method_with_property 属性的 getter 方法。需要注意的是,如果类中只包含该方法,那么 method_with_property 属性将是一个只读属性。

也就是说,在使用 DataSet 类时,无法对 method_with_property 属性重新赋值,运行代码会报错:

    class Rect:
        def __init__(self,area):
            self.__area = area
        @property
        def area(self):
            return self.__area
        @area.setter
    	def area(self, value):
       		self.__area = value
    rect = Rect(30)
    #直接通过方法名来访问 area 方法
    print("矩形的面积是:",rect.area)
    

想实现修改 area 属性的值,还需要为 area 属性添加 setter 方法,就需要用到 setter 装饰器,它的语法格式如下

@方法名.setter
def 方法名(self, value):
    代码块
@area.setter
def area(self, value):
	self.__area = value

在运行修改参数时,不会报错。

    rect.area = 90
    print("修改后的面积:",rect.area)

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

由于python进行属性的定义时,没办法设置私有属性,因此要通过@property的方法来进行设置。这样可以隐藏属性名,让用户进行使用的时候无法随意修改。

class DataSet(object):
    def __init__(self):
        self._images = 1
        self._labels = 2 #定义属性的名称
    @property
    def images(self): #方法加入@property后,这个方法相当于一个属性,这个属性可以让用户进行使用,而且用户有没办法随意修改。
        return self._images 
    @property
    def labels(self):
        return self._labels
l = DataSet()
#用户进行属性调用的时候,直接调用images即可,而不用知道属性名_images,因此用户无法更改属性,从而保护了类的属性。
print(l.images) # 加了@property后,可以用调用属性的形式来调用方法,后面不需要加()。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章