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
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容