私有属性和私有方法
- 私有属性就是对象不希望公开的属性
- 私有方法就是对象不希望公开的方法
定义方式
- 在定义属性或者方法时,在属性名或者方法名前增加两个下划线,定义的就是私有属性或者方法。
#案例
class Woman:
def __init__(self, name):
self.name = name
self.__age = 18
def __secret(self):
print("{}的年龄是{}".format(self.name, self.__age))
xiaomei = Woman("小美")
# 私有属性,在外界不能够被直接访问
print(xiaomei.__age)
xiaomei.__secret()
AttributeError Traceback (most recent call last)
in ()
14
15 # 私有属性,在外界不能够被直接访问
—> 16 print(xiaomei.__age)
17 xiaomei.__secret()
AttributeError: ‘Woman’ object has no attribute ‘__age’
伪私有属性和私有方法
提示:在开发中,不要使用这种方式,访问对象的私有属性或私有方法
- Python 中,并没有真正意义的私有。
- 在给属性、方法命名时,实际上是对名称做了一些特殊处理,使得外界无法访问到
- 处理方式:在名称前加上 _类名 => _类名__名称
#案例
class Woman:
def __init__(self, name):
self.name = name
self.__age = 18
def __secret(self):
print("{}的年龄是{}".format(self.name, self.__age))
xiaomei = Woman("小美")
# 私有属性,外部不能直接访问到
print(xiaomei._Woman__age)
# 私有方法,外部不能只调用
xiaomei._Woman__secret()
18
小美的年龄是18