python学习-面向对象进阶之属性property(七)
来源:互联网 发布:apache maven 编辑:程序博客网 时间:2024/06/07 07:45
属性property
1. 私有属性添加getter和setter方法
class Money(object): def __init__(self): self.__money = 0 def getMoney(self): return self.__money def setMoney(self, value): if isinstance(value, int): self.__money = value else: print("error:不是整型数字")
2. 使用property升级getter和setter方法
class Money(object): def __init__(self): self.__money = 0 def getMoney(self): return self.__money def setMoney(self, value): if isinstance(value, int): self.__money = value else: print("error:不是整型数字") money = property(getMoney, setMoney)
运行结果:
In [1]: from get_set import MoneyIn [2]: In [2]: a = Money()In [3]: In [3]: a.moneyOut[3]: 0In [4]: a.money = 100In [5]: a.moneyOut[5]: 100In [6]: a.getMoney()Out[6]: 100
3. 使用property取代getter和setter方法
@property
成为属性函数,可以对属性赋值时做必要的检查,并保证代码的清晰短小,主要有2个作用
- 将方法转换为只读
- 重新实现一个属性的设置和读取方法,可做边界判定
class Money(object): def __init__(self): self.__money = 0 @property def money(self): return self.__money @money.setter def money(self, value): if isinstance(value, int): self.__money = value else: print("error:不是整型数字")
运行结果
In [3]: a = Money()In [4]: In [4]: In [4]: a.moneyOut[4]: 0In [5]: a.money = 100In [6]: a.moneyOut[6]: 100
阅读全文
0 0
- python学习-面向对象进阶之属性property(七)
- python(七)上:面向对象进阶
- Python进阶之“属性(property)”详解
- Python进阶之“属性(property)”详解
- Python进阶之“属性(property)”详解
- Python进阶之“属性(property)”详解
- Python进阶之“属性(property)”详解
- python 进阶之属性函数property
- Python进阶之“属性(property)”详解
- Python进阶之“属性(property)”详解
- python之面向对象进阶
- python学习-面向对象进阶之元类(三)
- python学习-面向对象进阶之__slots__(五)
- python学习-面向对象进阶之私有化(六)
- python学习-面向对象进阶之闭包(八)
- python学习-面向对象进阶之迭代器(九)
- python学习-面向对象进阶之装饰器(十)
- python学习-面向对象进阶之生成器(十一)
- 实现高德地图定位
- MQactive
- 类与类的关系
- CSU 1562 Fun House(直线搜索)
- 洛谷P1006传纸条题解
- python学习-面向对象进阶之属性property(七)
- 变量
- Linux_内_存_管_理_精_述
- Java学习之迭代器Iterator
- git(八)-远程分支、别名、gitk与git gui
- 再用递归
- DFS 入门
- vb.net 教程 12-3 HtmlElement类 7
- 洛阳_hp,第二星期第一天