zoukankan      html  css  js  c++  java
  • 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!
  • 相关阅读:
    nohup
    wonder vscode plugins
    myhome vscode plugins
    virtural machine eth1
    单片机电子时钟的设计(期末课程设计)
    解决Eclipse中更改HTML页面后,浏览器查看页面无变化
    ASP.NET 中的 Session对象
    windows下mysql数据库导入导出
    TP5.1分表,partition分表实例,根据自增主键水平分表
    PHP操作mysql数据库分表的方法
  • 原文地址:https://www.cnblogs.com/roronoa-sqd/p/4900014.html
Copyright © 2011-2022 走看看