类中property和@property使用

property()函数


诞生原因: 希望使用类对象.属性的方式操作类中的属性

我们一直在用“类对象.属性”的方式访问类中定义的属性 其实这种做法是欠妥的,因为它破坏了类的封装原则。

正常情况下,类包含的属性应该是隐藏的,只允许通过类提供的方法来间接实现对类属性的访问和操作

因此,在不破坏类封装原则的基础上,为了能够有效操作属性,类中应包含读(或写)类属性的多个 getter(或 setter)方法,这样就可以通过“类对象.方法(参数)”的方式操作属性

Python 中提供了 property() 函数,可以实现在不破坏类封装原则的前提下,让开发者依旧使用**“类对象.属性”的方式操作类中的属性**

描述

property() 函数的作用是在新式类中返回属性值

维护数据的一致性

语法

属性名=property(fget=None, fset=None, fdel=None, doc=None)

参数

fget – 获取属性值的函数
fset – 设置属性值的函数
fdel – 删除属性值函数
doc – 属性描述信息

返回值

新式类属性

实例

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(getx, setx, delx, "I'm the 'x' property.")
c =C()
c.x = 2
2

如果 c 是 C 的实例化

c.x 将触发 getter

c.x = value 将触发 setter

del c.x 触发 deleter。

如果给定 doc 参数,其将成为这个属性值的 docstring,否则 property 函数就会复制 fget 函数的 docstring(如果有的话)。

实例2

class A:
    def __init__(self):
        pass
    def setx(self,x):
        pass
    def getx(self):
        return(self.)
    x = property(getx,setx)

x是类属性, 但赋值了property函数

a.x =就是函数的执行命令
所接受的值将赋给x,触发 setx(self,x),x的值传递到函数里

a.x
触发getx(self),返回实例的属性值

class Rect:
    def __init__(self):
        self.width = 0
        self.height = 0
        self.area = self.height*self.width
    
#     def setWidth(self,w):
#         self.width = w 不妥,此时修改了width但是前面算面积的width没有变,内部矛盾
    def setSize(self, size):#执行r0.size = 12,2时激发。将类属性size=(12,2)传递进来
        self.width,self.height = size #size是个容器,是个元组或者列表
        self.area  = self.width * self.height
        print('setSize():i worked like a common property, but actually, i am a method')
    
    def getSize(self):#执行r0.size时激发
        print('getSize():i am method too.')
        return (self.width,self.height) #返回的是元组
    
    size = property(getSize,setSize)#size是类属性,不是对象的属性

r0 = Rect()
r0.size = 12,2#
print('rect:',r0.size,"Area:",r0.area)
r0.size
setSize():i worked like a common property, but actually, i am a method
getSize():i am method too.
rect: (12, 2) Area: 24
getSize():i am method too.





(12, 2)

over,thank for your attention

发布了8 篇原创文章 · 获赞 0 · 访问量 21

猜你喜欢

转载自blog.csdn.net/weixin_44827144/article/details/105571746