@property和@setter和@getter

以下四种情况:

只读不可写

可写可读

不可写不可读(那你就没必要自己把这个成员变量封装到类里面了吧)

可写不可读(不存在)

所以常见情况其实只有两种.

 

 

@property @xxx.getter @xxx.setter 可写 可读 代码 备注
O X O O O hello1.py  
O X X X O hello2.py  

@property具备@xxx.setter效果,产生可读效果.

这三个装饰器件的效果是:

可读不一定可写

可写的一定可读

#--------------------------------------附录---------------------------------------------------------------

hello1.py

class Rectangle(object):

# 服务于返回数值
  @property
  def width(self):
    # 变量名不与方法名重复,改为true_width,下同
    print("@property called")
    return self.true_width


# 服务于设数值
  @width.setter
  def width(self, input_width):
    print("setter method called")
    print("input_width=",input_width)
    self.true_width = input_width
#-----------------------------------------------------------------
  @property
  def height(self):
    return self.true_height
  @height.setter
  #与property定义的方法名要一致
  def height(self, input_height):
    self.true_height = input_height
#-----------------------------------------------------------------
s = Rectangle()
# 与方法名一致
s.width = 1024
s.height = 768

print("*********下面是输出区域************")
print("s.width=",s.width)
print("s.true_width=",s.true_width)
print("--------------------")
print(s.height)

 

hello2.py

class Student(object):
#  服务于返回(可读)
    @property
    def birth(self):
        return self._birth

# 服务于设数值(可写)
    @birth.setter
    def birth(self, value):
        self._birth = value
#-----------------------------------------------------------------

#  服务于返回(可读)
    @property
    def age(self):
        return 2015 - self._birth

#-----------------------------------------------------------------

s = Student()
# 与方法名一致
s.birth = 1024
# s.age = 768#如果执行此句会报错

print("*********下面是输出区域************")
print("s.birth=",s.birth)
print("s.age=",s.age)

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章