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

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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值