@property特性

在某个函数前面加上这个@property装饰器,代表该方法为一个特性。一般不需要参数。调用时,不用加括号和参数,不能被赋值。property是一种特殊的属性,访问它时会执行一段功能(函数)然后返回值

 import math
 2 class Circle:
 3     def __init__(self,radius): #圆的半径radius
 4         self.radius=radius
 5 
 6     @property
 7     def area(self):
 8         return math.pi * self.radius**2 #计算面积
 9 
10     @property
11     def perimeter(self):
12         return 2*math.pi*self.radius #计算周长
13 
14 c=Circle(10)
15 print(c.radius)
16 print(c.area) #可以向访问数据属性一样去访问area,会触发一个函数的执行,动态计算出一个值
17 print(c.perimeter) #同上
18 '''
19 输出结果:
20 314.1592653589793
21 62.83185307179586
22 '''
原文地址:https://www.cnblogs.com/gwj99/p/7649779.html