设为首页 加入收藏

TOP

Python内置装饰器@property(一)
2019-09-03 03:39:45 】 浏览:132
Tags:Python 内置 装饰 @property

前言


我们可以看一下@property源码中给的实例和解释



复制代码
 1 Decorators make defining new properties or modifying existing ones easy:
 2
 3
 4 class C(object):
 5    @property
 6    def x(self):
 7        "I am the 'x' property."
 8        return self._x
 9
10    @x.setter
11    def x(self, value):
12        self._x = value
13
14    @x.deleter
15    def x(self):
16        del 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.__name
19
20    def set_name(self, name):
21        """通过外部传参的方式绑定属性"""
22        self.__name = name
23
24
25 if __name__ == '__main__':
26    user = UserInfo()
27    # 绑定name属性
28    user.set_name(["超哥", "linux超"])
29    print("我的名字是:", 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.__name
18
19    @name.setter
20    def name(self, name):
21        if isinstance(name, str):
22            self.__name = name
23        else:
24            raise TypeError("The name must be str")
25
26
27 if __name__ == '__main__':
28    user = UserInfo()
29    # 绑定属性
30    user.name = "linux超"
31    print("我的名字是", user.name)
32    user.name = ["linux超", "超哥"]
33    print("我的名字是", 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
 

首页 上一页 1 2 下一页 尾页 1/2/2
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇带你了解 Java内存模型 下一篇Python接口自动化之mock模块基本..

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目