Python类私有字段和属性使用

2025-10-16 11:07:01

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

声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
猜你喜欢