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/

  • 相关阅读:
    注解
    es
    集合collection-map-list-set
    spring boot Configuration Annotation Proessor not found in classpath
    mvn
    linux_elasticsearch_jdk_ssh
    Floyd算法学习
    同一个job,不同shell之间传递参数
    jenkins post build tasks插件中log text参数的使用说明
    一个强大的jenkins 批量修改job的插件Configuration Slicing
  • 原文地址:https://www.cnblogs.com/fcyworld/p/6187431.html
Copyright © 2011-2022 走看看