Python @property特性的使用
阿新 • • 發佈:2018-12-08
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('[email protected] 修飾器的獲取者、設定者、刪除者-----------')
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'
執行結果為: