鱼C论坛

 找回密码
 立即注册
查看: 1751|回复: 0

[技术交流] python学习【@property】

[复制链接]
发表于 2021-7-31 14:49:47 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
一、作用:

@peoperty是python的装饰器,可以将方法转换成相同名称的只读属性,创建只读属性,防止属性被篡改。





二、具体使用:

(1)@property使方法可以像属性一样调用

  1. class test():
  2.     @property
  3.     def method_with_property(self):
  4.         return 13
  5.    
  6.     def method_without_property(self):
  7.         return 16
  8.    
  9.    
  10. test1 = test()
  11. print(test1.method_with_property)
  12. print(test1.method_without_property())
复制代码



(2)@property配合属性使用,防止属性被篡改

  1. class test1():
  2.     def __init__(self):
  3.         self._row = 3
  4.         self._col = 4
  5.    
  6.     @property
  7.     def row(self):
  8.         return self._row
  9.    
  10.     @property
  11.     def col(self):
  12.         return self._col

  13. test2 = test1()
  14. print(test2.col)
  15. print(test2.row)
复制代码


说明:本篇是根据https://zhuanlan.zhihu.com/p/64487092整理学习得到的,仅作为个人学习笔记使用。

本帖被以下淘专辑推荐:

小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-5-20 06:18

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表