Python:特性(property)

2017-10-30  本文已影响0人  我是周先生
class Circle:
    def __init__(self, r):
        self._r = r
# 特性:如果调用特性,则用户只能访问不能设置
    @property
    def re(self):
        return self._r
# 设置器:专门提供给特性使用,用来修改特性的值
# @特性名.setter
    @re.setter
    def re(self,num):
        if type(num) is int:
            self._r=num
        else:
            print('请设置整数值')
# 删除器:通过del删除某个特性时,如果定义了删除器,则该操作会执行删除其中的代码
#    @特性名.deleter
    @re.deleter
    def re(self):
        print('不能删除该属性,否则会影响其他功能的实现')

cir = Circle(10);
print(cir.re)
cir.re=20
print(cir.re)
del cir.re
print(cir._r)
上一篇 下一篇

猜你喜欢

热点阅读