Python中使用property实现类的特性
来源:互联网 发布:js获取某个元素的位置 编辑:程序博客网 时间:2024/06/07 13:27
Python中的特性是一个函数,但是在使用的形式上看起来更像是一个属性。针对一个对象来说,与属性相比,特性是不能够随意添加的。而对象的属性,默认情况下添加是十分简单的。
下面通过代码展示如何使用property实现特性:
class MyClass:
def __init__(self,val1,val2):
self.val1 = val1
self.val2 = val2
@property
def Sum(self):
return self.val1 + self.val2
obj =MyClass(34,45)
print(obj.Sum)
程序的执行结果如下:
grey@DESKTOP-3T80NPQ:/mnt/e/01_workspace/02_programme_language/03_python/03_OOP/2017/08$python property.py
79
从上面的结果来看,特性在调用的时候跟属性是差不多的。如果通过类似方法的调用则会报错,下面修改代码如下:
class MyClass:
def __init__(self,val1,val2):
self.val1 = val1
self.val2 = val2
@property
def Sum(self):
return self.val1 + self.val2
obj =MyClass(34,45)
print(obj.Sum)
# wrong way tocall the Sum property
print(obj.Sum())
程序执行结果如下:
grey@DESKTOP-3T80NPQ:/mnt/e/01_workspace/02_programme_language/03_python/03_OOP/2017/08$python property.py
79
Traceback (mostrecent call last):
File "property.py", line 12, in<module>
print(obj.Sum())
TypeError: 'int'object is not callable
- Python中使用property实现类的特性
- python中@property的使用
- Python 类的魔力特性之一:property
- Python中property属性(特性)的理解
- 关于python中@property的使用
- 关于python中@property的使用
- python中property的使用实例
- 【python】@property 的使用
- python property的使用
- Python中C++类特性的实现原理
- 对于Python中@property的理解和使用
- 16.3 Python descriptor-property(特性)
- 在Python中使用属性Property
- pb中实现使用属性(property)访问类的私有字段
- pb中实现使用属性(property)访问类的私有字段
- 【@property的特性】
- 【OC】@property的特性
- 飘逸的python - property及实现lazy property
- 解决hao123胁持chrome主页问题
- web周末jsp
- linearlayout布局的属性 gravity layout_gravity layout_weight
- react-native 开发app之坑
- matlab对1/x,1/x^2怎么表示,在cvx工具箱下
- Python中使用property实现类的特性
- java爬虫--step1--简单网页获取
- 关于委托小实例
- 【Angular学习】Angular环境配置
- 虚拟机Ubuntu与s5pv210的ping
- 二叉树中和为某一值的路径
- 记录开始写博客的第一天
- 冒泡排序
- javascript基本知识点