[关闭]
@SuHongjun 2020-06-01T16:26:11.000000Z 字数 1871 阅读 145

Python-Day xx:类和对象 - 中级知识2:property

Python 2020春季学期


使用@property

  1. #只读属性
  2. class Person(object):
  3. def __init__(self,name,birth,gender='unknown'):
  4. self.name = name
  5. self._birth = birth
  6. self.gender = gender
  7. @property #定义了一个只读属性 age
  8. def age(self): #只能有一个self参数
  9. return 2020 - self._birth
  10. Jack = Person('Jack',1995)
  11. print(Jack.age)
  12. #输出25

property属性的定义和调用要注意一下几点:
1. 定义时,在实例方法的基础上添加 @property 装饰器;并且仅有一个self参数
2. 调用时,无需括号

  1. class Person(object):
  2. @property
  3. def birth(self): #可读写属性
  4. return self._birth
  5. @birth.setter #可写属性, @property创建出来的装饰器
  6. def birth(self, value):
  7. self._birth = value
  8. @property
  9. def age(self): #只读属性
  10. return 2015 - self._birth
  11. >>> Jack = Person()
  12. >>> Jack.birth = 1998
  13. >>> Jack.age
  14. 17
  1. #新式类中的property有三种访问方式,并分别对应了三个被 @property、@方法名.setter、@方法名.deleter 修饰的方法
  2. class Goods(object):
  3. def __init__(self):
  4. # 原价
  5. self.original_price = 100
  6. # 折扣
  7. self.discount = 0.8
  8. @property
  9. def price(self):
  10. # 实际价格 = 原价 * 折扣
  11. new_price = self.original_price * self.discount
  12. return new_price
  13. @price.setter
  14. def price(self, value):
  15. self.original_price = value
  16. @price.deleter
  17. def price(self):
  18. print('del')
  19. del self.original_price
  20. # ############### 调用 ###############
  21. obj = Goods()
  22. obj.price # 自动执行 @property 修饰的 price 方法,并获取方法的返回值
  23. obj.price = 123 # 自动执行 @price.setter 修饰的 price 方法,并将 123 赋值给方法的参数
  24. del obj.price # 自动执行 @price.deleter 修饰的 price 方法

使用property升级getter和setter方法

  1. class Money(object):
  2. def __init__(self):
  3. self.__money = 0
  4. def getMoney(self):
  5. return self.__money
  6. def setMoney(self, value):
  7. if isinstance(value, int):
  8. self.__money = value
  9. else:
  10. print("error:不是整型数字")
  11. # 定义一个属性,当对这个money设置值时调用setMoney,当获取值时调用getMoney
  12. money = property(getMoney, setMoney) #这是Python2遗留的方法
  13. a = Money()
  14. a.money = 100 # 调用setMoney方法
  15. print(a.money) # 调用getMoney方法

使用property取代getter和setter方法,可做边界判定

  1. class Money(object):
  2. def __init__(self):
  3. self.__money = 0
  4. # 使用装饰器对money进行装饰,那么会自动添加一个叫money的属性,当调用获取money的值时,调用装饰的方法
  5. @property
  6. def money(self):
  7. return self.__money
  8. # 使用装饰器对money进行装饰,当对money设置值时,调用装饰的方法
  9. @money.setter
  10. def money(self, value):
  11. if isinstance(value, int):
  12. self.__money = value
  13. else:
  14. print("error:不是整型数字")
  15. a = Money()
  16. a.money = 100
  17. print(a.money)
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注