zoukankan      html  css  js  c++  java
  • python property

    假设定义了一个类:C,该类必须继承自object类,有一私有变量_x
    class C:
     def __init__(self):
      self.__x=None
      1.现在介绍第一种使用属性的方法:
      在该类中定义三个函数,分别用作赋值、取值和删除变量(此处表达也许不很清晰,请看示例)
     def getx(self):
      return self.__x
     def setx(self,value):
      self.__x=value
     def delx(self):
      del self.__x
     x=property(getx,setx,delx,'')

    property函数原型为property(fget=None,fset=None,fdel=None,doc=None),所以根据自己需要定义相应的函数即可。

      现在这个类中的x属性便已经定义好了,我们可以先定义一个C的实例c=C(),然后赋值c.x=100,取值y=c.x,删除:del c.x。是不是很简单呢?请看第二种方法
      2.下面看第二种方法(在2.6中新增)
      首先定义一个类C:
    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
     同一属性的三个函数名要相同哦。。

  • 相关阅读:
    模块和包专区
    递归函数,三级菜单专区
    内置函数和匿名函数专区
    迭代器和生成器专区
    函数进阶专区
    初始函数专区
    题解 P6282 【[USACO20OPEN]Cereal S】
    题解 P6281 【[USACO20OPEN]Social Distancing S】
    题解 P6281 【[USACO20OPEN]Social Distancing S】
    第5题:棋盘
  • 原文地址:https://www.cnblogs.com/whiteprism/p/6204148.html
Copyright © 2011-2022 走看看