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!
  • 相关阅读:
    进入用友通:提示"由于文件不可访问,内存磁盘空间不足无法打开ufsystem数据库"...
    HDOJ 1069 Monkey and Banana
    HDOJ 1087 Super Jumping! Jumping! Jumping!
    HDOJ 1209 Clock
    CodeForces Round #185 (Div. 2)A,B,C
    HDOJ 1465 不容易系列之一
    HDOJ 1114 PiggyBank
    HDOJ 1280 前m大的数
    HDOJ 1495 非常可乐
    HDOJ 1284 钱币兑换问题
  • 原文地址:https://www.cnblogs.com/roronoa-sqd/p/4900014.html
Copyright © 2011-2022 走看看