美文网首页
Day6面向对象高级编程1/3

Day6面向对象高级编程1/3

作者: 林清猫耳 | 来源:发表于2018-03-31 01:16 被阅读15次

    使用slots

    正常情况下,当我们定义了一个class,创建了一个class的实例后,我们可以给该实例绑定任何属性和方法,这就是动态语言的灵活性。

    class Student(object):
        pass
    

    还可以尝试给实例绑定一个方法:

    >>> def set_age(self, age): # 定义一个函数作为实例方法
    ...     self.age = age
    ...
    >>> from types import MethodType
    >>> s.set_age = MethodType(set_age, s) # 给实例绑定一个方法
    >>> s.set_age(25) # 调用实例方法
    >>> s.age # 测试结果
    25
    

    但是,给一个实例绑定的方法,对另一个实例是不起作用的:

    >>> s2 = Student() # 创建新的实例
    >>> s2.set_age(25) # 尝试调用方法
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    AttributeError: 'Student' object has no attribute 'set_age'
    

    为了给所有实例都绑定方法,可以给class绑定方法:

    >>> def set_score(self, score):
    ...     self.score = score
    ...
    >>> Student.set_score = set_score
    

    给class绑定方法后,所有实例均可调用:

    >>> s.set_score(100)
    >>> s.score
    100
    >>> s2.set_score(99)
    >>> s2.score
    99
    

    通常情况下,上面的set_score方法可以直接定义在class中,但动态绑定允许我们在程序运行的过程中动态给class加上功能,这在静态语言中很难实现。
    但是,如果我们想要限制实例的属性怎么办?比如,只允许对Student实例添加nameage属性。
    为了达到限制的目的,Python允许在定义class的时候,定义一个特殊的__slots__变量,来限制该class实例能添加的属性:

    class Student(object):
        __slots__ = ('name', 'age') # 用tuple定义允许绑定的属性名称
    
    >>> s = Student() # 创建新的实例
    >>> s.name = 'Michael' # 绑定属性'name'
    >>> s.age = 25 # 绑定属性'age'
    >>> s.score = 99 # 绑定属性'score'
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    AttributeError: 'Student' object has no attribute 'score'
    

    由于'score'没有被放到__slots__中,所以不能绑定score属性,试图绑定score将得到AttributeError的错误。
    __slots__定义的属性仅对当前类实例起作用,对继承的子类是不起作用的


    使用@property

    Python内置的@property(性能)装饰器就是负责把一个方法变成属性调用的。

    class Student(object):
    
        @property
        def score(self):
            return self._score        # 一定要在score前面加下划线 否则会出现下面情况
    
        @score.setter
        def score(self,value):
            if not isinstance(value,int):
                raise ValueError('score must be a integer!')
            if value < 0 or value > 100:
                raise ValueError('score must beween 0 ~ 100!')
            self._score = value
    
    >>> s = Student()
    >>> s.score = 60
    Traceback (most recent call last):
      File "<pyshell#80>", line 1, in <module>
        s.score = 60
      File "C:\Python36x32bit\practice.py", line 13, in score
        self.score = value
      File "C:\Python36x32bit\practice.py", line 13, in score
        self.score = value
      File "C:\Python36x32bit\practice.py", line 13, in score
        self.score = value
      [Previous line repeated 492 more times]
      File "C:\Python36x32bit\practice.py", line 11, in score
        if value < 0 or value > 100:
    RecursionError: maximum recursion depth exceeded in comparison
    

    注释

    1. self.是对属性的访问,使用它的时候编译器会判断_是否为空,为空的话自动实例化。会自动访问getset方法。
    2. _是对实例变量的访问,我们没有实例化它,不能使用。
    3. 对类里局部变量访问使用_,外部变量则用self.
    4. getter方法中,不要再使用self。否则会重复调用getter方法,造成死循环。

    正常情况下,把一个getter方法变成属性,只需要加上@property就可以了,此时,@property本身又创建了另一个装饰器@score.setter,负责把一个setter方法变成属性赋值,于是,我们就拥有一个可控的属性操作:

    >>> s = Student()
    >>> s.score = 60 # OK,实际转化为s.set_score(60)
    >>> s.score # OK,实际转化为s.get_score()
    60
    >>> s.score = 9999
    Traceback (most recent call last):
      ...
    ValueError: score must between 0 ~ 100!
    

    还可以定义只读属性,只定义getter方法,不定义sette方法就是一个只读属性:

    class Student(object):
    
        @property
        def birth(self):
            return self._birth
    
        @birth.setter
        def birth(self,value):     #可读写属性
            self._birth = value
    
        @property
        def age(self):        #只读属性, 因为age可以根据birth和当前时间计算出来
            return 2018 - self._birth
    
    >>> s = Student()
    >>> s.birth = 1995
    >>> s.age
    23
    >>> s.age = 24
    Traceback (most recent call last):
      File "<pyshell#90>", line 1, in <module>
        s.age = 24
    AttributeError: can't set attribute
    

    相关文章

      网友评论

          本文标题:Day6面向对象高级编程1/3

          本文链接:https://www.haomeiwen.com/subject/djjwcftx.html