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

栏目: Python · 发布时间: 7年前

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

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

一个矩形类型,设置大小,然后获取大小。

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并不是一个函数,它是一个有很多方法的类。具体原理可以自行了解下。

工程文件下载:


以上所述就是小编给大家介绍的《少说话多写代码之Python学习049——类的成员(property函数)》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

The Web Application Hacker's Handbook

The Web Application Hacker's Handbook

Dafydd Stuttard、Marcus Pinto / Wiley / 2011-9-27 / USD 50.00

The highly successful security book returns with a new edition, completely updated Web applications are the front door to most organizations, exposing them to attacks that may disclose personal infor......一起来看看 《The Web Application Hacker's Handbook》 这本书的介绍吧!

MD5 加密
MD5 加密

MD5 加密工具

html转js在线工具
html转js在线工具

html转js在线工具

HEX CMYK 转换工具
HEX CMYK 转换工具

HEX CMYK 互转工具