zoukankan      html  css  js  c++  java
  • Python学习笔记捌——面向对象高级编程

    __slots__特殊变量的使用:

    由于Python是动态语言,允许先编写类,然后在创建实例的时候添加属性或者方法;而__slots__特殊变量就是,限制往类里添加属性的;

    在创建类的时候,使用__slots__ =('name','age'),就是在创建实例时候,只允许添加绑定name和age两个属性;注意!__slots__只对当前类有效,不会作用于子类;

    @property装饰器:为了实现数据的封装,不把属性暴露在外面,所以如果想访问实例内部属性的话,就需要使用get和set方法,但是这样不方便,于是就出现了@property装饰器,他的作用是把函数变成属性,来访问调用。

    >>> class Student(object):
    ...    def get_score(self):
    ...      return self._score
    ...    def set_score(self,value):
    ...      if not isinstance(value,int):
    ...        raise ValueError('value must be integer')
    ...      if value < 0 or value > 100:
    ...        raise ValueError('value must between 0 and 100')
    ...      self._score = value
    ...
    >>> s=Student()
    >>> s.set_score(60)
    >>> s.score
    Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
    AttributeError: 'Student' object has no attribute 'score'
    >>> s.get_score()
    60
    >>> s.set_score(120)
    Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
    File "<stdin>", line 8, in set_score
    ValueError: value must between 0 and 100
     注!这种情况就是没有装饰器的保护数据不暴露的方法。但是有了装饰器,可以将方法变成属性来调用,就方便多了。

    >>> class Student2(object):
    ...    @property
    ...    def score(self):
    ...       return self._score
    ...    @score.setter
    ...    def score(self,value):
    ...      if not isinstance(value,int):
    ...        raise verror('score must be integer')
    ...      if value<0 or value>100:
    ...        raise verror('score must between 0~100')
    ...      self._score=value
    ...
    >>> s=Student
    >>> s=Student()
    >>> s.score=99
    >>> s.score

    99

  • 相关阅读:
    C++中左移<<的使用
    学会构造素数序列
    有关lower_bound()函数的使用
    Codeforces Round #166 (Div. 2)
    暴力swap导致TLE问题解决办法
    memset的正确使用
    Codeforces Round #297 (Div. 2)
    Codeforces Round #170 (Div. 2)B
    Codeforces Round #176 (Div. 2)
    C/C++ sort函数的用法
  • 原文地址:https://www.cnblogs.com/ooOO00/p/5452092.html
Copyright © 2011-2022 走看看