Python 私有属性和私有方法

应用场景

工作中,对象的某些属性或方法只在内部使用,不对外纰漏

在定义属性和方法时,名称前加 两个下划线

'''
私有属性&私有方法
'''

class Man:
    def __init__(self, name):
        self.name = name
        self.__age = 45

    def __search(self):
        print(f"年龄:{self.__age}")


lhc = Man("令狐冲")

访问私有属性和私有方法

'''
print(lhc.__age)
Traceback (most recent call last):
  File "E:/worksp_py/hardwary/100day/fifty/Man.py", line 16, in <module>
    print(lhc.__age)
AttributeError: 'Man' object has no attribute '__age'
'''

'''lhc.__search()
Traceback (most recent call last):
  File "E:/worksp_py/hardwary/100day/fifty/Man.py", line 25, in <module>
    lhc.__search()
AttributeError: 'Man' object has no attribute  __search  '''

说明

使用伪私有属性和方法的访问形式可以看到私有信息,但是在工作中不推荐使用

print(lhc._Man__age)  # 45
lhc._Man__search()  # 年龄:45

输出

45
年龄:45

 

posted @ 2023-06-09 10:25  晓枫的春天  阅读(26)  评论(0编辑  收藏  举报