import math
class Circle:
def __init__(self, radius):
self.__radius = radius # 设置私有属性,不让用实例.__radius访问
def __get_radius(self):
return round(self.__radius, 1)
def __set_radius(self, radius):
if not isinstance(radius, (int, float)):
raise TypeError('wronge type')
self.__radius = radius
@property
def S(self):
return self.__radius ** 2 * math.pi #property第二种方法,加装饰器@property
@S.setter
def S(self, s):
self.__radius = math.sqrt(s / math.pi) #property第二种方法,加装饰器@S.setter
R = property(fget=__get_radius, fset=__set_radius) #property其中一种方法,定义类变量
c = Circle(5.712)
print(c.R) #调用了get_radius方法获取半径
c.R = 8.886 #调用了set_radius,设置半径
print(c.R)
print('=======================')
print(c.S) #调用S方法获取面积
c.S = 3.14 #设置面积
print(c.R)
print(c.S)
==================================================================
5.7
8.9
=======================
248.063284953733
1.0
3.14
【python】使用property函数为类创建可管理属性fget\fset\fdel
最新推荐文章于 2022-01-07 22:06:23 发布