Python @property特性的使用

1、实例:

Shape.py文件:

#-*- coding:utf-8 -*-
import math
class Point:
    def __init__(self,x=0,y=0):
        self.x=x;
        self.y=y;
    def distance_from_origin(self):
        return math.hypot(self.x,self.y)
    def __eq__(self,other):
        return self.x==self.x and self.y==self.y
    def __repr__(self):
        return "Point({0.x!r},{0.y!r})".format(self)
    def __str__(self):
        return "({0.x!r},{0.y!r})".format(self)
class Circle(Point):
    def __init__(self,radius,x=0,y=0):
        super().__init__(x,y)
        self.__radius=radius;
    #获取私有属性的值,radius=circle.radius;会执行这个函数
    @property
    def radius(self):
        #返回私有属性
        return self.__radius;
    #设置私有属性值,circle.radius=23
    @radius.setter
    def radius(self,radius):
        assert self.radius>0,'radius must be nonzero and non-negative'
        self.__radius=radius;
    #删除私有属性 del circle.radius会执行这个函数
    @radius.deleter
    def radius(self):
        #删除属性
        del self.__radius

    @property
    def edge_distance_from_origin(self):
        return abs(self.distance_from_origin()-self.radius)
    # @property
    # def area(self):
    #     return math.pi*(self.radius**2)
    def area(self):
        return math.pi*(self.radius**2)
    area=property(area);
    def circumference(self):
        return 2*math.pi*self.radius
    def __eq__(self, other):
        return self.radius==other.radius and super().__eq__(other)
    def __repr__(self):
        return "Circle({0.radius!r},{0.x!r},{0.y!r})".format(self)
    def __str__(self):
        return repr(self)

ShapeAlt.py文件:

#-*- coding:utf-8 -*-
import Shape
circle=Shape.Circle(5,28,45)
print(circle.area)
#print(circle.area())#TypeError: 'float' object is not callable
print(circle.edge_distance_from_origin)
#print(circle.edge_distance_from_origin())#TypeError: 'float' object is not callable
print('--------@property修饰器的获取者、设置者、删除者-----------')
radius=circle.radius;
print(radius)

circle.radius=6
print(circle.radius)


del circle.radius
#print(circle.radius)#AttributeError: 'Circle' object has no attribute '_Circle__radius'

运行结果为:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值