面向对象——property

1.property特性

  • property是一种特殊的属性,访问它时会执行一段功能(函数)然后返回值
  • 将一个类的函数定义成特性以后,对象再去使用的时候obj.name,根本无法察觉到name是执行了一个函数然后计算出来的,注意的是:不能对obj.name进行赋值,否则报错,抛出异常
  • 这种特性的使用方式遵循了统一访问的原则
  •  1 class Room:
     2     def __init__(self,name,owner,weight,length,height):
     3         self.name = name
     4         self.owner = owner
     5         self.__weight = weight
     6         self.__length = length
     7         self.__height = height
     8     @property
     9     def tell_area(self):
    10         return self.__weight * self.__length
    11 r = Room('教室','LuffyCity',10,10,3)
    12 print(r.tell_area)#100
    13 r.tell_area = 1   #报错,不能对其进行赋值
    View Code
原文地址:https://www.cnblogs.com/GraceZ/p/8081504.html