1. 程式人生 > >7-4 如何創建可管理的對象屬性

7-4 如何創建可管理的對象屬性

__new__ one set err BE self math ase doc

技術分享圖片

技術分享圖片
>>> help(property)
Help on class property in module __builtin__:

class property(object)
 |  property(fget=None, fset=None, fdel=None, doc=None) -> property attribute
 |  
 |  fget is a function to be used for getting an attribute value, and likewise
 |  fset is a function for setting, and
fdel a function for deling, an | attribute. Typical use is to define a managed attribute x: | | class C(object): | def getx(self): return self._x | def setx(self, value): self._x = value | def delx(self): del self._x | x = property(getx, setx, delx, "I‘m the ‘x‘ property.
") | | Decorators make defining new properties or modifying existing ones easy: | | class C(object): | @property | def x(self): | "I am the ‘x‘ property." | return self._x | @x.setter | def x(self, value): | self._x = value | @x.deleter
| def x(self): | del self._x | | Methods defined here: | | __delete__(...) | descr.__delete__(obj) | | __get__(...) | descr.__get__(obj[, type]) -> value | | __getattribute__(...) | x.__getattribute__(name) <==> x.name | | __init__(...) | x.__init__(...) initializes x; see help(type(x)) for signature | | __set__(...) | descr.__set__(obj, value) | | deleter(...) | Descriptor to change the deleter on a property. | | getter(...) | Descriptor to change the getter on a property. | | setter(...) | Descriptor to change the setter on a property. | | ---------------------------------------------------------------------- | Data descriptors defined here: | | fdel | | fget | | fset | | ---------------------------------------------------------------------- | Data and other attributes defined here: | | __new__ = <built-in method __new__ of type object> | T.__new__(S, ...) -> a new object with type S, a subtype of T
help(property)

property()三個參數分別是訪問方法,設置方法。

from math import pi

class Circle(object):
    def __init__(self,radius):
        self.radius = radius

    def getRadius(self):
        return self.radius
    def setRadius(self,value):
        if not isinstance(value,(int,long,float)):
            raise ValueError(wrong data type,please slecet int or long or float)
        self.radius = value

    def getArea(self):
        return self.radius ** 2 * pi
    R = property(getRadius,setRadius)


c = Circle(3.2)

print (c.getArea())

print (c.R)                #以屬性方式訪問,實際上調用的是getRadius

c.R = 4                    #以屬性方式訪問,實際上調用的是setRadius

print(c.R)          
print(c.getArea())

輸出結果:

32.1699087728

3.2

4

50.2654824574

7-4 如何創建可管理的對象屬性