python中property属性的介绍及其应用详解
作者:三国小梦 时间:2022-09-26 03:21:36
Python的property属性的功能是:property属性内部进行一系列的逻辑计算,最终将计算结果返回。
使用property修饰的实例方法被调用时,可以把它当做实例属性一样
property的用法1——装饰器方式
在类的实例方法上应用@property装饰器
class Test:
def __init__(self):
self.__num = 100
@property
def num(self):
print("--get--")
return self.__num
@num.setter
def num(self, num):
print("--set--")
self.__num = num
t = Test()
print(t.num)
t.num = 1
"""
--get--
100
--set--
"""
property属性的定义和调用要注意一下几点:
定义时,在实例方法的基础上添加 @property 装饰器;并且仅有一个self参数。
调用时,无需括号。
经典类中的属性只有一种访问方式,其对应被 @property 修饰的方法。
新式类中的属性有三种访问方式,并分别对应了三个被@property、@方法名.setter、@方法名.deleter修饰的方法。
Python中的类有经典类和新式类,新式类的属性比经典类的属性丰富。( 如果类继object,那么该类是新式类 ),python3中的类都是新式类。
property的用法2——类属性方式
当使用类属性的方式创建property属性时,经典类和新式类无区别
class Test:
def __init__(self):
self.__num = 100
def setNum(self, num):
print("--set--")
self.__num = num
def getNum(self):
print("--get--")
return self.__num
# 注意:要先写get方法,再写set方法
aa = property(getNum, setNum)
t = Test()
print(t.aa)
t.aa = 1
来源:https://www.cnblogs.com/lxy0/p/11424213.html
标签:python,property,属性,应用
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
键盘上下键的操作代码(选择)
2008-06-10 12:28:00
Python实现微信自动好友验证,自动回复,发送群聊链接方法
2021-10-22 00:11:23
![](https://img.aspxhome.com/file/2023/7/63227_0s.jpg)
Web开发的改良
2009-06-25 14:34:00
php递归删除目录与文件的方法
2023-09-12 02:02:02
巧用特殊的空格字符
2009-04-10 18:32:00
关于php开启错误提示的总结
2023-11-04 10:46:21
php时间不正确的解决方法
2023-11-18 07:33:15
Oracle 数据库中创建合理的数据库索引
2009-07-02 12:31:00
[翻译]寻找圣杯 In Search of the Holy Grail
2008-11-12 13:10:00
![](https://img.aspxhome.com/file/UploadPic/up/2008111213334212.gif)
3个asp简单技巧
2009-11-26 20:55:00
良好的css代码注释
2008-07-01 13:02:00
数据库技巧——MySQL十大优化技巧
2011-01-31 16:44:00
![](https://img.aspxhome.com/file/UploadPic/20111/2011131175530832s.jpg)
ACCESS入门教程:用向导建立数据库
2008-01-17 12:46:00
![](https://img.aspxhome.com/file/UploadPic/20081/17/20081171368486s.gif)
Oracle建立二进制文件索引的方法
2010-07-18 13:29:00
在ASP中如何使用类class
2007-09-16 17:17:00
Python实现运行其他程序的四种方式实例分析
2023-08-03 00:48:24
![](https://img.aspxhome.com/file/2023/1/61741_0s.png)
用滤镜使网页图片产生旋转效果
2007-11-03 11:36:00
![](https://img.aspxhome.com/file/UploadPic/20072/20072311370301s.jpg)
IE7异常CSS 导致内存破坏漏洞
2009-11-30 12:52:00
轻松接触SQL Server 2000实例的命名规则
2009-01-23 13:44:00
使用XMLhttp生成html页面
2007-08-17 11:21:00