zoukankan      html  css  js  c++  java
  • 【Python】@property的用法

      设想我们要给一个student()类的一个实例s,添加一个score的属性,比如:

      s.score=999999

      这个值明显是不合理的,但是它却是可行的,怎么能改变这种情况?我们能想到的就是用类方法

      class student:

        def setsore:

          #code

        def getsocre:

          #code

      这样是可行的,但是没有使用属性直接设置方便,这时候就可以用到@property装饰器了。

      当使用@property装饰器对getattr方法进行装饰的时候,会自动产生一个对setattr方法

    进行装饰的装饰器getattr.setattr  这样,就可以在实例中直接使用属性对getattr和setattr方

    法进行调用

    例子:

     1 class screen:
     2     @property
     3     def width(self):
     4         return self._width
     5 
     6 
     7     @width.setter          #装饰getwidth方法,即装饰width方法产生的装饰器
     8     def width(self, width):    #注意,在这里setwidth方法和getwidth方法名一样
     9         self._width = width    
    10 
    11 
    12     @property
    13     def height(self):
    14         return self._height
    15 
    16 
    17     @height.setter
    18     def height(self, h):
    19         self._height = h
    20 
    21 
    22     @property
    23     def resolution(self):
    24         return self._width * self._height
    25 
    26 s = screen()
    27 s.width = 1024
    28 s.height = 768
    29 print(s.resolution)
    30 assert s.resolution == 786432, '1024 * 768 = %d ?' % s.resolution

    参考资料:廖雪峰的官方网站http://www.liaoxuefeng.com/

  • 相关阅读:
    c++中的内存管理【转载】
    c++中dynamic_cast、static_cast、reinterpret_cast和const_cast作用
    c++中的顶层const和底层const
    c++赋值操作符需要确保自我赋值的安全性问题
    二分法查找
    Servlet基础总结
    java 正则表达式:有丶东西
    HTTP协议初步认识
    Java synchronized到底锁住的是什么?
    ECMA Script 6新特性之解构赋值
  • 原文地址:https://www.cnblogs.com/fcyworld/p/6187431.html
Copyright © 2011-2022 走看看