首页 > 编程语言 > 详细

python类中私有属性和方法

时间:2021-01-19 09:23:30      阅读:27      评论:0      收藏:0      [点我收藏+]

1. 类中定义私用属性和方法

在属性和方法名称前加"__"这个属性和方法就变成了私有成员,私有成员在外部无法直接调用

class C():
    def __init__(self):
        self.name = "C"
        self.__age = 18
    
    def __fn4(self):
        print("fn4")

cc = C()
print(cc.age)       # AttributeError: ‘C‘ object has no attribute ‘age‘
print(cc.__age)     # AttributeError: ‘C‘ object has no attribute ‘__age‘
cc.fn4()    # AttributeError: ‘C‘ object has no attribute ‘fn4‘
cc.__fn4()       # AttributeError: ‘C‘ object has no attribute ‘__fn4‘

 

2. 访问私有属性

提供公有的getter、setter方法

class C():
    def __init__(self):
        self.name = "C"
        self.__age = 18
    
    def __fn4(self):
        print("fn4")

    def get_age(self):
        return self.__age

    def set_age(self, new_age):
        self.__age = new_age

cc = C()
print(cc.get_age())     # 18
cc.set_age(25)
print(cc.get_age())     # 25

 

python类中私有属性和方法

原文:https://www.cnblogs.com/liuxuelin/p/14295933.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!