019: class, objects and instance: property
2016-01-25 21:35
495 查看
属性在本质上来讲是一组方法,但是调用的时候却如同字段,换句话说,其实就是对字段的一种封装,在设定和读取的时候,可以很轻易的添加逻辑,而其调用方式其不会改变
在Pyhon中可以用@property来定义:
运行结果:
在Pyhon中可以用@property来定义:
class Book(object): def __init__(self, title, price): self._title = title self._price = price @property def price(self): return "${}".format(self._price) @price.setter def price(self, value): self._price = value @price.deleter def price(self): del self._price book = Book("Python Basic", 100) print(book.price) book.price = 200 print(book.price) del book.price print(book.price)
运行结果:
$100 $200 Traceback (most recent call last): File "C:\Users\Miles\python\class_object\20160125_1.py", line 26, in <module> print(book.price) File "C:\Users\Miles\python\class_object\20160125_1.py", line 8, in price return "${}".format(self._price) AttributeError: 'Book' object has no attribute '_price'
相关文章推荐
- Objective-C之成魔之路【16-使用文件】
- Objective C类方法load和initialize的区别
- @dynamic 模拟NSManagedObject类的内部实现,AFN的非常规用法
- [[dic objectForKey:@"name"] description]
- Object-C类、方法、构造函数(2)
- Objective-C 在Categroy中创建属性(Property)
- Python内部机制-PyTypeObject对象
- objective-c之各种数值
- Objective-C位运算符
- 【Ubuntu 64bit】libz.so.1: cannot open shared object file: No such file or directory 【Android NDK】
- 【Ubuntu 64bit】libz.so.1: cannot open shared object file: No such file or directory 【Android NDK】
- error C2712: Cannot use __try in functions that require object unwinding
- error C2712: Cannot use __try in functions that require object unwinding
- [iOS]setValue和setObject区别
- ArcGIS&nbsp;Objects开发-QI接口查…
- 4.3 Routing -- Generated Objects
- Python内部机制-PyObject对象
- OOP (Objects and Classes )
- 深入学习Objective-C语言的动态特性
- iOS:Objective-c的MD5/SHA1加密算法的实现