019: class, objects and instance: property
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了019: class, objects and instance: 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‘
以上是关于019: class, objects and instance: property的主要内容,如果未能解决你的问题,请参考以下文章
hausaufgabe--python 39 -- objects and class
017: class, objects and instance: class method