私有属性

class Test():
    def __init__(self,name,age):
        self.name = name
        self.__age = age

    def fun(self):
        print(self.__age)

#私有属性只能内部访问,外部是不能访问的
obj=Test('abc',18)
print(obj.name)
# print(obj.__age)#会出错  #私有属性只能内部访问,外部是不能访问的
obj.fun()  #打印结果:18

#如果想外部访问,python也是可以拿到私有属性的
print(obj._Test__age)  #打印结果:18

##私有字段子类中也不能访问

猜你喜欢

转载自www.cnblogs.com/chvv/p/9975920.html