Property
#property
#内置装饰器函数,只在面向对象中使用
from math import pi
class Circle:
def __init__(self,r ):
self.r = r
@property
def perimeter(self):#property属性不能传递任何参数
return 2*pi*self.r
@property
def area(self):
return self.r**2*pi
c1 = Circle(5)
# print(c1.area()) #不加property目前定义的是个方法,圆的面积应该是属性,故用@property装饰
print(c1.perimeter) #调用不用加()
print(c1.area)
利用Setter修改Property装饰的变量
class Person:
def __init__(self, name):
self.__name = name
@property
def name(self):
return self.__name + 'sb'
@name.setter #定义一个方法.setter,必须和property装饰同名的方法
def name(self,new_name):
self.__name = new_name
#实现了property装饰的变量的修改操作
tiger = Person('泰哥')
print(tiger.name)
tiger.name = '全部'
print(tiger.name)
>>>>
泰哥sb
全部sb
![](https://img2018.cnblogs.com/blog/1473797/201809/1473797-20180919130707953-1406087280.png)
- Property的实际应用场景 --某个属性需要经过一些计算或操作而得出的结果,通常定义为一个方法然后用Property装饰
class Goods:
discount = 0.5
def __init__(self,name, price):
self.name = name
self.__price = price #折扣前价格定义为私有的
@property
def price(self): #折扣后的价格定义为一个方法并用property装饰,进行一些操作
return self.__price*Goods.discount
apple = Goods('苹果', 5)
print(apple.price)
Property的删除-deleter
class Person:
def __init__(self,name):
self.__name = name
@property
def name(self):
return self.__name
@name.deleter #property装饰的变量.deleter
def name(self):
del self.__name#执行删除私有变量
@name.setter #设置一个新的变量
def name(self,new_name): #可以传递一个变量
self.__name = new name
brother2 = Person('二哥')
print(brother2.name)
del brother2.name #删除某个私有变量
print(brother2.name)
>>>>
二哥
File "C:/Users/jwang2/PycharmProjects/PlayPy/Demo/S9-day25-封装.py", line 139, in <module>
print(brother2.name)
File "C:/Users/jwang2/PycharmProjects/PlayPy/Demo/S9-day25-封装.py", line 131, in name
return self.__name
AttributeError: 'Person' object has no attribute '_Person__name'
![](https://img2018.cnblogs.com/blog/1473797/201809/1473797-20180919132650696-2883681.png)