您的位置:首页 > 移动开发 > Objective-C

019: class, objects and instance: property

2016-01-25 21:35 495 查看
属性在本质上来讲是一组方法,但是调用的时候却如同字段,换句话说,其实就是对字段的一种封装,在设定和读取的时候,可以很轻易的添加逻辑,而其调用方式其不会改变

在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'
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: