python内置装饰器@property
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了python内置装饰器@property,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含4430字,纯文字阅读大概需要7分钟。
内容图文

前言
今天来说一下@property装饰器,这是个python内置的装饰器,主要是作用是把类中的一个方法变为类中的一个属性,并且使定义属性和修改现有属性变的更容易
我们可以看一下@property源码中给的实例和解释
1 Decorators make defining new properties or modifying existing ones easy: 2 3 4class C(object): 5 @property 6def x(self): 7"I am the ‘x‘ property." 8return self._x 910 @x.setter 11def x(self, value): 12 self._x = value 1314 @x.deleter 15def x(self): 16del self._x
没错,龟叔给的解释就是这个装饰器会把定义新属性和对现有的属性的修改变的更简单,那么传统的方法在绑定属性和访问属性时是什么样的呢?
实例
1 """ 2 ------------------------------------ 3 @Time : 2019/7/4 20:57 4 @Auth : linux超 5 @File : python_property.py 6 @IDE : PyCharm 7 @Motto: Real warriors,dare to face the bleak warning,dare to face the incisive error! 8 @QQ : 28174043@qq.com 9 @GROUP: 878565760 10 ------------------------------------ 11 """ 12 13 14 class UserInfo(object): 15 16 def get_name(self): 17 """ 通过类的方法访问类中的属性 """ 18 return self.__name1920def set_name(self, name): 21"""通过外部传参的方式绑定属性"""22 self.__name = name 232425if__name__ == ‘__main__‘: 26 user = UserInfo() 27# 绑定name属性28 user.set_name(["超哥", "linux超"]) 29print("我的名字是:", user.get_name())
执行结果
我的名字是: [’超哥’, ‘linux超’]
Process finished with exit code 0
这种方式在绑定属性,获取属性时显的很是繁琐,而且无法保证数据的准确性,从执行结果看来,名字应该是个字符串才对,然而输出结果却是个列表,这并不符合实际规则
而且也没有通过直接访问属性,修改属性的方式那么直观
我们对代码稍作改动,并使用@property装饰器来实现
1 """ 2 ------------------------------------ 3 @Time : 2019/7/4 22:02 4 @Auth : linux超 5 @File : python_class.py 6 @IDE : PyCharm 7 @Motto: Real warriors,dare to face the bleak warning,dare to face the incisive error! 8 @QQ : 28174043@qq.com 9 @GROUP: 878565760 10 ------------------------------------ 11 """ 12 13 14 class UserInfo(object): 15 @property 16 def name(self): 17 return self.__name1819 @name.setter 20def name(self, name): 21if isinstance(name, str): 22 self.__name = name 23else: 24raise TypeError("The name must be str") 252627if__name__ == ‘__main__‘: 28 user = UserInfo() 29# 绑定属性30 user.name = "linux超"31print("我的名字是", user.name) 32 user.name = ["linux超", "超哥"] 33print("我的名字是", user.name)
执行结果
我的名字是 linux超 Traceback (most recent call last): File " D:/LingMengPython16/LingMengPython16/cnblogs/python_class.py ", line 32, in <module> user.name = ["linux超", "超哥"] File "D:/LingMengPython16/LingMengPython16/cnblogs/python_class.py", line 24, in name raise TypeError("The name must be str") TypeError: The name must be str Process finished with exit code 1
经过优化后的代码我们可以看到当绑定的属性并非是一个字符串类型时,就会报错,而且我们可以直接通过类似访问属性的方式来绑定属性,访问属性,这样就更加直观了
这里有个点需要注意,@name.setter中name这个名字极其被他修饰的方法名字与@property修改的方法名必须保持一致,否则会报错
其中@name.setter装饰器是因为使用了@property后他本身创建的装饰器
其实呢,我觉得@perproty装饰器并不仅仅只用来绑定属性和访问属性,还可以用来在类的外部访问私有成员属性
先来看个类的外部直接访问私有成员的实例
1 """ 2 ------------------------------------ 3 @Time : 2019/7/4 20:57 4 @Auth : linux超 5 @File : python_property.py 6 @IDE : PyCharm 7 @Motto: Real warriors,dare to face the bleak warning,dare to face the incisive error! 8 @QQ : 28174043@qq.com 9 @GROUP: 878565760 10 ------------------------------------ 11 """ 12 13 14 class UserInfo(object): 15 16 def __init__ (self, name, age): 17 self.__name = name 18 self.__age = age 1920if__name__ == ‘__main__‘: 21 user = UserInfo(‘linux超‘, 18) 22print(user.__name)
执行结果
Traceback (most recent call last): File " D:/LingMengPython16/LingMengPython16/cnblogs/python_property.py ", line 22, in <module> print(user.__name) AttributeError: ‘UserInfo‘ object has no attribute ‘__name‘ Process finished with exit code 1
没错,程序是没办法运行成功的,因为python不允许你在类的外部访问类中的私有成员,这么做其实是为了保护数据的安全性
那么这时候我们也可以使用@property装饰器来访问类的属性
1 """ 2 ------------------------------------ 3 @Time : 2019/7/4 20:57 4 @Auth : linux超 5 @File : python_property.py 6 @IDE : PyCharm 7 @Motto: Real warriors,dare to face the bleak warning,dare to face the incisive error! 8 @QQ : 28174043@qq.com 9 @GROUP: 878565760 10 ------------------------------------ 11 """ 12 13 14 class UserInfo(object): 15 16 def __init__ (self, name): 17 self.__name = name 1819 @property 20def name(self): 21"""通过类的方法访问类中的私有属性"""22return self.__name2324if__name__ == ‘__main__‘: 25 user = UserInfo(‘linux超‘) 26print("获取name属性:", user.name)
执行结果
获取name属性: linux超
Process finished with exit code 0
这样就能访问类的私有成员属性了
那么其实我个人认为,相对于绑定属性来说这种方式用的比较多,当你不想子类继承父类时,防止子类修改父类的属性,那么你完全就可以使用这种方法来避免属性被修改,而且在子类和类的外部还可以正常访问这个私有属性
总结
@property装饰器主要用来改变一个方法为一个属性,且需要注意几点
1. 被此装饰器装饰的方法不能传递任何除self外的其他参数
2.当同时使用@property和@x.setter时 需要保证x以及被@x.setter修改的方法名字与@property修改的方法名字必须保持一致
原文:https://www.cnblogs.com/linuxchao/p/linuxchao-property.html
内容总结
以上是互联网集市为您收集整理的python内置装饰器@property全部内容,希望文章能够帮你解决python内置装饰器@property所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。