📜  Python属性装饰器 - @property

📅  最后修改于: 2022-05-13 01:55:42.087000             🧑  作者: Mango

Python属性装饰器 - @property

Python中的装饰器功能包装在一个函数中,将几个功能附加到现有代码,然后返回它。众所周知,方法和函数是可调用的,因为它们可以被调用。因此,装饰器也是返回可调用对象的可调用对象。这也称为元编程,因为在编译时,程序的一部分会改变程序的另一部分。

注意:有关详细信息,请参阅Python中的装饰器

Python @property 装饰器

@property装饰器是Python中的内置装饰器,它有助于轻松定义属性,而无需手动调用内置函数property()。它用于从指定的 getter、setter 和 deleter 作为参数返回类的属性属性。

现在,让我们看一些示例来说明Python中@property装饰器的使用:
示例 1:

# Python program to illustrate the use of
# @property decorator
  
# Defining class
class Portal:
  
    # Defining __init__ method
    def __init__(self):
        self.__name =''
      
    # Using @property decorator
    @property
      
    # Getter method
    def name(self):
        return self.__name
      
    # Setter method
    @name.setter
    def name(self, val):
        self.__name = val
  
    # Deleter method
    @name.deleter
    def name(self):
       del self.__name
  
# Creating object
p = Portal();
  
# Setting name
p.name = 'GeeksforGeeks'
  
# Prints name
print (p.name)
  
# Deletes name
del p.name
  
# As name is deleted above this 
# will throw an error
print (p.name)
输出:
GeeksforGeeks

## An error is thrown
Traceback (most recent call last):
  File "main.py", line 42, in 
    print (p.name)
  File "main.py", line 16, in name
    return self.__name
AttributeError: 'Portal' object has no attribute '_Portal__name'

这里,@property 装饰器用于定义Portal类中的属性name ,它具有三个名称相似的方法(getter、setter 和 deleter),即name() ,但它们具有不同数量的参数。其中, @property标记的方法name(self)是一个 getter 方法, name(self, val)是一个 setter 方法,因为它用于设置属性__name的值,因此它用@name.setter标记。最后,带有@name.deleter标记的方法是一个删除器方法,它可以通过setter 方法删除分配的值。但是,删除器是在关键字del的帮助下调用的。
示例 2:

# Python program to illustrate the use of
# @property decorator
  
# Creating class
class Celsius:
      
    # Defining init method with its parameter
    def __init__(self, temp = 0):
        self._temperature = temp
  
    # @property decorator
    @property
      
    # Getter method
    def temp(self):
          
        # Prints the assigned temperature value
        print("The value of the temperature is: ")
        return self._temperature
  
    # Setter method
    @temp.setter
    def temp(self, val):
          
        # If temperature is less than -273 than a value
        # error is thrown
        if val < -273:
            raise ValueError("It is a value error.")
          
        # Prints this if the value of the temperature is set
        print("The value of the tempereture is set.")
        self._temperature = val
  
  
# Creating object for the stated class 
cel = Celsius();
  
# Setting the temperature value
cel.temp = -270
  
# Prints the temperature that is set
print(cel.temp)
  
# Setting the temperature value to -300
# which is not possible so, an error is 
# thrown
cel.temp = -300
输出:
The value of the tempereture is set.
The value of the temperature is:
-270

# An error is thrown
Traceback (most recent call last):
  File "main.py", line 47, in 
    cel.temp = -300
  File "main.py", line 28, in temp
    raise ValueError("It is a value error.")
ValueError: It is a value error.

此处,由于指定的温度值必须高于 -273,因此会引发值错误。但这里是-300。因此,抛出一个值错误。