Python类私有字段和属性使用

 时间:2026-02-12 04:46:30

1、打开Python开发工具IDLE.新建‘property.py’文件,并写代码如下:

class student:

    def __init__(self,name,idCard,bankAccount):

        self.name = name

        self.id = idCard

        self.__bankAccount = bankAccount

s1 = 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,idCard,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 = 321

print (s1.name)

print (s1.AccountNo)

@AccountNo.setter是AccountNo属性的赋值函数,注意使用时候直接用‘=’就行。

Python类私有字段和属性使用

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

张三

321

Python类私有字段和属性使用

  • 教师节贺卡可以怎么制作?
  • 【药品说明书】果糖二磷酸钠注射液
  • 如何挑选好的五常大米?
  • 煎蛋图片设计
  • 童心向党共战疫情手抄报
  • 热门搜索
    昆明旅游社 长治旅游景点大全 凤凰山旅游 重庆 旅游 张家界旅游价格 和儿子旅游爬山做了儿子带套 北京旅游指南 金佛山旅游攻略 湖南旅游局 过年去哪里旅游比较好