属性在本质上来讲是一组方法,但是调用的时候却如同字段,换句话说,其实就是对字段的一种封装,在设定和读取的时候,可以很轻易的添加逻辑,而其调用方式其不会改变
在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:UsersMilespythonclass_object20160125_1.py", line 26, in <module> print(book.price) File "C:UsersMilespythonclass_object20160125_1.py", line 8, in price return "${}".format(self._price) AttributeError: 'Book' object has no attribute '_price'