python系列之(三)OOP面向对象编程的高级用法

1、限制对实例属性的调用和设置
1.1要限制实例属性的绑定范围,使用__slots__关键字
1.2为防止错误的变量设置导致类方法调用出错,提高程序健壮性,设置getter和setter方法来间接设置和调用属性

class student(object):
  # getter func
  def get_score(self):  
    return self._score
  # setter func
  def set_score(self, input_score):  
    if input_score is not int:
      print('Input is not a integer!')
    if input > 100 or input < 0:
      print('0-100 is allowed!')
    self._score = input_score

s = student()
s.get_score()
s.set_score(66)

1.3简化getter和setter的调用,把方法当作属性来看待,使用@property关键字,如果不使用@score.setter,就只能读不能写

class student(object):
  # getter func
  @property
  def score(self):  
    return self._score

  # setter func
  @score.setter
  def score(self, input_score):  
    if input_score is not int:
      print('Input is not a integer!')
    if input > 100 or input < 0:
      print('0-100 is allowed!')
    self._score = input_score

s = student()
s.score
s.score = 66

你可能感兴趣的:(python系列之(三)OOP面向对象编程的高级用法)