少说话多写代码之Python学习049——类的成员(property函数)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/yysyangyangyangshan/article/details/84455039

 如果要访问类中的私有变量,根据面向对象原则,是不能直接访问的,这里有一个访问器的概念。将私有变量进行封装,公布出访问的方法。比如下面这样,
 一个矩形类型,设置大小,然后获取大小。

class Rectangle:
    def __init__(self):
        self.width=0
        self.height=0
    def setSize(self,size):
        self.width,self.height=size
    def getSize(self):
        return  self.width,self.height


r=Rectangle()
r.width=100
r.height=61.8
print(r.getSize())
r.setSize((1000,618))
print(r.getSize())

输出

(100, 61.8)
(1000, 618)

对于矩形类来说,setSize和getSize就是一个访问器,其对应的值是width和height。如果矩形类中增加了其他字段,势必每个字段都要公布访问器,即写一个get和set方法。Python中有一个函数可以很好解决这个问题。就是property函数。
对于刚才的矩形类,我们做一个改进,

_metachclass_=type
class Rectangle1:
    def __init__(self):
        self.width=0
        self.height=0
    def setSize(self,size):
        self.width,self.height=size
    def getSize(self):
        return  self.width,self.height
    size=property(getSize,setSize)

r1=Rectangle1()
r1.width=10
r1.height=6.18
print(r1.size)

r1.size=1,0.618
print(r1.width)
print(r1.height)

输出

(10, 6.18)
1
0.618

在Rectangle1类中,用property创建了一个属性size。size虽然取决于setSize和getSize的计算,但是使用起来其实是可以当作属性的。而实际上property并不是一个函数,它是一个有很多方法的类。具体原理可以自行了解下。

工程文件下载:https://download.csdn.net/download/yysyangyangyangshan/10805525

猜你喜欢

转载自blog.csdn.net/yysyangyangyangshan/article/details/84455039
今日推荐