设为首页 加入收藏

TOP

python 面向对象七 property() 函数和@property 装饰符
2017-12-19 17:25:04 】 浏览:194
Tags:python 面向 对象 property 函数 @property 装饰

一、property引入

为了使对象的属性不暴露给调用者和进行属性值检查,设置了访问属性的接口函数,使用函数访问属性,并可以在函数内部检查属性。

 1 >>> class Student(object):
 2       def get_score(self):
 3           return self._score
 4       def set_score(self, value):
 5           if not isinstance(value, int):
 6               raise ValueError('score must be an integer!')
 7           if value < 0 or value > 100:
 8               raise ValueError('score must between 0 ~ 100!')
 9           self._score = value
10 
11         
12 >>> s = Student()
13 >>> s.set_score(10)  
14 >>> s.get_score()
15 10

这样每次访问属性的时候,都要访问函数,相比较之前直接访问属性的方式,变得麻烦了。property可以解决这个麻烦,虽然还是函数,但是可以像属性一样访问。

二、property装饰器方法:

>>> class C:
      def __init__(self):
          self.__x = None
      @property
      def x(self):
          return self.__x
      @x.setter
      def x(self,value):
          self.__x=value
      @x.deleter
      def x(self):
          del self.__x
    
>>> c = C()
>>> c.x
>>> c.x = 100
>>> c.x
100

三、property函数方法:

>>> class C:
        def __init__(self):
            self.__x = None
        def getx(self):
            return self.__x
        def setx(self, value):
            self.__x = value
        def delx(self):
            del self.__x
        x = property(fget=getx,fset=setx,fdel=delx, doc='')

    
>>> c = C()
>>> c.x = 100
>>> c.x
100
>>> del c.x
>>> c.x
Traceback (most recent call last):
  File "<pyshell#64>", line 1, in <module>
    c.x
  File "<pyshell#59>", line 5, in getx
    return self.__x
AttributeError: 'C' object has no attribute '_C__x'

 

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇异常处理问题 下一篇小白学爬虫-设置Selenium+Chrome..

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目