网站首页 美食营养 游戏数码 手工爱好 生活家居 健康养生 运动户外 职场理财 情感交际 母婴教育 时尚美容

Python类私有字段和属性使用

时间:2024-10-31 14:48:56

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中私有字段以两个下划线开头

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'程序报错,是因为私有字段不能类外直接访问。

Python类私有字段和属性使用

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 就标注为属性,注意在使用时不需要加括号,像直接访问字段一样就行。

Python类私有字段和属性使用

4、F5运行程序,私有字段的值被打印出来:张三123

Python类私有字段和属性使用

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属性的赋值函数,注意使用时候直接用‘=’就行。

Python类私有字段和属性使用

6、F5运行程序,私有字段的值被成功赋值并打印出来:张三321

Python类私有字段和属性使用
© 2025 小知经验
信息来自网络 所有数据仅供参考
有疑问请联系站长 site.kefu@gmail.com