Python @property特性的使用

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/huanhuanq1209/article/details/82621978

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'

运行结果为:

猜你喜欢

转载自blog.csdn.net/huanhuanq1209/article/details/82621978
今日推荐