1、打开Python开发工具IDLE.新建‘property.py’文件,并写代码如下:class student: def __init__(self,name,idCard,bankAccount): self.name = name self.id = idCard self.__bankAccount = bankAccounts1 = student('张三',1,123)print (s1.name)print (s1.__bankAccount)定义了一个student类,并实例化s1对象,__bankAccount是类的私有字段,python中私有字段以两个下划线开头
2、F5运行程序,Shell中打印信息如下:张三Traceback (most recent call last): File "C:/Users/123/AppData/Local/Programs/Python/Python36/property.py", line 9, in <module> print (s1.__bankAccount)AttributeError: 'student' object has no attribute '__bankAccount'程序报错,是因为私有字段不能类外直接访问。
3、Python中通过属性的方式来访问私有字段,代码如下:class 衡痕贤伎student: def __init__(self,name,id潮贾篡绐Card,bankAccount): self.name = name self.id = idCard self.__bankAccount = bankAccount @property def AccountNo(self): return self.__bankAccount s1 = student('张三',1,123)print (s1.name)print (s1.AccountNo)在类的方法上加@property 就标注为属性,注意在使用时不需要加括号,像直接访问字段一样就行。
4、F5运行程序,私有字段的值被打印出来:张三123
5、需要更改私有字段的值也是通过属性方式倦虺赳式。代码如下:class student: def __init__(self,name,idCard,bankAccount): self.name = name self.id = idCard self.__bankAccount = bankAccount @property def AccountNo(self): return self.__bankAccount @AccountNo.setter def SetAccountNo(self,bankAccount): self.__bankAccount = bankAccount s1 = student('张三',1,123)s1.SetAccountNo = 321print (s1.name)print (s1.AccountNo)@AccountNo.setter是AccountNo属性的赋值函数,注意使用时候直接用‘=’就行。
6、F5运行程序,私有字段的值被成功赋值并打印出来:张三321