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类私有字段和属性使用

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类私有字段和属性使用

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类私有字段和属性使用
  • 教师节贺卡可以怎么制作?
  • 【药品说明书】果糖二磷酸钠注射液
  • 如何挑选好的五常大米?
  • 煎蛋图片设计
  • 童心向党共战疫情手抄报
  • 热门搜索
    中国水上旅游网 华东五市旅游报价 冰峪沟旅游攻略 北京周边旅游景点大全 新疆旅游注意事项 苏州旅游地图 北京长城旅游 春节旅游攻略 西安旅游集团 十月旅游