美文网首页
Python中@property的使用讲解

Python中@property的使用讲解

作者: SevenBy | 来源:发表于2018-02-11 00:32 被阅读779次

装饰器(decorator)可以给函数动态加上功能,对于类的方法,装饰器一样起作用。Python内置的@property装饰器就是负责把一个方法变成属性调用的:


下面写一个例子,如有不懂的同学可以联系我邮箱

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
__author__='byx54192@gmail.com'

class Student(object):

    @property #将birth 转换为属性,外部可是直接s.birth访问
    def birth(self):
        return self._birth

    @birth.setter #@property本身又创建了另一个装饰器@score.setter,负责把一个setter方法变成属性赋值
    def birth(self, value):
        if value>0 and value<100:
            self._birth = value
        else:
            raise ValueError('birth must between 0~100')

    @property #将age方法转换为属性,外部调用时,可以用s.age访问。
    def age(self):
        return 2015 - self._birth
s= Student()
s.birth=10
print(s.age)
print(s.birth)

练习

请利用@property给一个Screen对象加上width和height属性,以及一个只读属性resolution:

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
__author__='byx54192@gmail.com'

class Screen(object):
    @property
    def width(self):
        return self._width
    @width.setter
    def width(self,value):
        if value!=768:
            return 0
        self._width=value

    @property    
    def height(self):
        return self._height
    @height.setter
    def height(self,value):
        if value!=1024:
            return 0
        self._height=value

    @property
    def resolution(self):
        return self._width*self._height
s=Screen()
s.width=768
s.height=1024
print('resolution=',s.resolution)
if s.resolution == 786432:
    print('测试通过!')
else:
    print('测试失败!')
Python中@property的使用讲解

相关文章

  • Python中@property的使用讲解

    装饰器(decorator)可以给函数动态加上功能,对于类的方法,装饰器一样起作用。Python内置的@prope...

  • Python中property中的小坑

    刚刚了解了python中的@property的使用,property本质是python中的一个内置修饰器。使用大概...

  • python中@property的使用

    今天遇到一个问题: 报错了,经过改正后的代码如下: 想不到吧,一个小小的下划线竟然是罪魁祸首。不过还是不能理解,为...

  • python学习-@property

    视频讲解:读源码需要的python技能: decorator property:https://www.bilib...

  • Python进阶——面向对象

    1. Python中的@property   @property是python自带的装饰器,装饰器(decorat...

  • 16 python中@property的使用

    参考资料:https://www.liaoxuefeng.com/wiki/001374738125095c955...

  • Python @property 详解

    一、概述 python中 @property 是python的一种装饰器,是用来修饰方法的。我们可以使用@pro...

  • Python使用@property

    在绑定属性时,如果我们直接把属性暴露出去,虽然写起来很简单,但是,没办法检查参数,导致可以把成绩随便改: 这显然不...

  • python 使用 @property

    引用-廖雪峰 背景 在设置属性时,可以直接把属性暴露出去,这个简单,但是会导致被随意修改属性值。 为了避免上面值被...

  • python 使用@property

    比get、set方法实现起来更简单

网友评论

      本文标题:Python中@property的使用讲解

      本文链接:https://www.haomeiwen.com/subject/fofhtftx.html