"""
有时候,我们希望设计的类内的有些函数或者变量只允许这个类自身访问。比如 __init__ 函数,本身用于类的初始化调用,
没有被实例调用的必要。
私有化:
在要私有的属性名前加上 __ ,如: self.__name = name # 此时,__name 只能在类内使用,实例化对象将无法访问
在要私有的函数名前加上 __ ,如: def __func(self): # 此时,__func 只能在类内使用,实例化对象将无法访问
"""
class ClassPrivate:
"""用于展示私有属性和方法使用的类"""
def __init__(self):
self.__word = 'Hello Python!' # 私有属性,实例对象无法访问
def pprint(self):
print(self.__word)
def __pprint(self): # 私有方法,实例对象无法访问
print(self.__word)
show = ClassPrivate()
show.pprint()
# print(show.__word)
"""实例访问私有属性或方法,将报错:
Traceback (most recent call last):
File "E:/PycharmProjects/Object_Oriented/Private.py", line 31, in <module>
print(show.__word)
AttributeError: 'ClassPrivate' object has no attribute '__word'
"""