• Python -- OOP高级 -- __slots__、@property



    __slots__属性可以设置 允许被设置的属性

    class Student:
        __slots__ = ("name", "age")

    >>> s = Student()
    
    >>> s.age = 25
    
    >>> s.name = "Zoro"
    
    >>> s.score = 100
    Traceback (most recent call last):
      File "<ipython-input-38-b5a9e82f869f>", line 1, in <module>
        s.score = 100
    
    AttributeError: 'Student' object has no attribute 'score'

    当一个类中设置__slots__属性时,只有()中的属性可以动态设置


    @property装饰器

    class Student():
        @property
        def score(self):
            return self._score
            
        @score.setter
        def score(self, value):
            if not isinstance(value, int):
                raise ValueError("Score must be an integer!")
            if value < 0 or value > 100:
                raise ValueError("Score must between 0~100!")
            self._score = value
    
        @score.deleter
        def score(self):
            del self._score

    >>> s = Student()
    >>> s.score = 100
    >>> s.score
    Out[43]: 100
    >>> s.score = 101 Traceback (most recent call last): File "<ipython-input-44-84f4bf77cd8e>", line 1, in <module> s.score = 101 File "C:/Users/SQD/Desktop/@property.py", line 18, in score raise ValueError("Score must between 0~100!") ValueError: Score must between 0~100! >>> s.score = "abc" Traceback (most recent call last): File "<ipython-input-45-179a51b0c6cf>", line 1, in <module> s.score = "abc" File "C:/Users/SQD/Desktop/@property.py", line 16, in score raise ValueError("Score must be an integer!") ValueError: Score must be an integer! >>> del s.score

    把一个getter方法变成属性,只需要加上@property就可以了,此时,@property本身又创建了另一个装饰器@score

    还可以设置只读属性:只有getter,没有setter

    class Student:
        @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 = 1989
    >>> s.age
    Out[57]: 26
    
    >>> s.age = 27
    Traceback (most recent call last):
      File "<ipython-input-58-03895bf010a3>", line 1, in <module>
        s.age = 27
    
    AttributeError: can't set attribute
    KEEP LEARNING!
  • 相关阅读:
    7月6日实习日志
    7月5日实习日志
    7月4日实习日志
    emacs设置tab缩进
    {{badmatch, {error, eexist}}
    windows下使用emacs+plink远程编辑erlang文件
    cowboy跨域请求处理
    erlang的base64解码问题
    Erlang-VM节点启动名冲突问题
    laya在微信小游戏中加载BitmapFont失效的问题
  • 原文地址:https://www.cnblogs.com/roronoa-sqd/p/4900014.html
Copyright © 2020-2023  润新知