0
点赞
收藏
分享

微信扫一扫

Python装饰器------@property


文章目录

  • ​​引言​​
  • ​​@property​​
  • ​​设置可读写属性​​
  • ​​设置只读属性​​

引言

首先我们定义一个Person类,这里多说一点在Python3.x中Person()与Person(object)是一样的,默认帮你加载了Object类

class Person():

def get_height(self):
return self._height

def set_height(self, value):
self._height = value


if __name__ == '__main__':
hhh = Person()
hhh.set_height(10)
print(hhh.get_height())

通常我们会像这样去设置和调用类中的某个属性,但是,上面的调用方法又略显复杂,这时候就是推荐@property的时候了,它既能检查参数,又可以用类似属性这样简单的方式来访问类的变量

@property

Python内置的​​@property​​​装饰器作用就是把一个方法变成属性调用,如果我们想把一个getter(实在不知道怎么解释就用Java里的这个东西来说吧)方法变成属性,这时候只需要在def 定义函数之前加上一个​​@property​

设置可读写属性

我们以引言部分的​​Person()​​​类为例,这时,​​@property​​​本身又为其创建了另一个装饰器​​@height.setter​​,负责把一个setter方法变成属性赋值;

下面附上参考代码:

class Person():

@property
def height(self):
return self._height

@height.setter
def height(self, value):
self._height = value


if __name__ == '__main__':
hhh = Person()
hhh.height = 10
print(hhh.height)

在这个时候我们就能像调用属性一样去对height进行操作,这无疑是简单了许多

设置只读属性

🌂Add:特别提示,如果我们需要属性只读那么就只需要使用​​@property​​​,而如果再加上​​@某个方法.setter​​那么就成为了可读写属性,emmm还是举个例子吧

class Person():

@property
def height(self):
return self._height

@height.setter
def height(self, value):
self._height = value

@property
def money(self):
return self._height*10

这时候,我们去调用就会打印出100

hhh = Person()
hhh.height = 10
print(hhh.money)

而如果我们 使用 ​​hhh.money = 100​​​时
python就会报错​​​AttributeError: can't set attribute​​,不能设置属性,好了大概就先总结这么多,周末愉快!


举报

相关推荐

0 条评论