python类中私有属性和方法

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

 

posted @ 2021-01-19 00:25  foreast  阅读(630)  评论(0编辑  收藏  举报