提示信息

Python property()

浮光 已关注

The property() function in Python is used to create and return a property object. It allows defining a method as a getter, setter or a deleter of an attribute.

Syntax:

  1. property(fget=None, fset=None, fdel=None, doc=None)

Parameters:
- fget: Optional. A method to get the value of the attribute.
- fset: Optional. A method to set the value of the attribute.
- fdel: Optional. A method to delete the attribute.
- doc: Optional. A string to provide the documentation for the attribute.

Return value:
- A property object that can be assigned to a class attribute. When accessed, the methods defined by fget, fset, and fdel will be called accordingly.

Example usage:

  1. class Circle:
  2. def __init__(self, radius):
  3. self._radius = radius
  4. @property
  5. def radius(self):
  6. return self._radius
  7. @radius.setter
  8. def radius(self, value):
  9. if value >= 0:
  10. self._radius = value
  11. else:
  12. raise ValueError("Radius cannot be negative!")
  13. @radius.deleter
  14. def radius(self):
  15. del self._radius
  16. # Creating an instance of Circle
  17. c = Circle(5)
  18. # Accessing the radius attribute using the property
  19. print(c.radius) # Output: 5
  20. # Setting a new value to the radius attribute
  21. c.radius = 10
  22. print(c.radius) # Output: 10
  23. # Trying to set a negative value to the radius attribute
  24. c.radius = -5 # Raises a ValueError
  25. # Deleting the radius attribute
  26. del c.radius
  27. print(c.radius) # AttributeError: 'Circle' object has no attribute '_radius'

In the above example, @property decorator is used to define a getter method for the radius attribute, @radius.setter decorator is used to define a setter method, and @radius.deleter decorator is used to define a deleter method.

    遇到难题? "AI大模型GPT4.0、GPT" 是你的私人解答专家! 点击按钮去提问......
浮光 关注 已关注

最近一次登录:2023-10-09 15:58:57   

暂时还没有签名,请关注我或评论我的文章
×
免费图表工具,画流程图、架构图