当前位置: 代码迷 >> 综合 >> 【python】使用property函数为类创建可管理属性fget\fset\fdel
  详细解决方案

【python】使用property函数为类创建可管理属性fget\fset\fdel

热度:60   发布时间:2023-12-05 13:04:10.0
import mathclass 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@propertydef S(self):return self.__radius ** 2 * math.pi      #property第二种方法,加装饰器@property@S.setterdef S(self, s):self.__radius = math.sqrt(s / math.pi)    #property第二种方法,加装饰器@S.setterR = 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
  相关解决方案