Python学习笔记—— 面向对象2. 私有属性和私有方法
应用场景及定义方式
· 在实际开发中,对象的某些属性和方法可能只希望在对象的内部使用,而不希望在外部被访问到
· 在定义方法或属性时,在属性名或者方法名前增加两个下划线,定义的就是私有属性或方法
class Women:
def __init__(self,name):
self.name = name
self.__age = 18
def secret(self):
print("%s 的年龄是 %d"%(self.name,self.__age))
xiaofang = Women("小芳")
#私有属性在外界不能被直接访问
print(xiaofang.__age)
Traceback (most recent call last):
File “F:/Python编程/练习/test.py”, line 11, in
print(xiaofang.__age)
AttributeError: ‘Women’ object has no attribute ‘__age’
私有属性在外界不能被直接访问
class Women:
def __init__(self,name):
self.name = name
self.__age = 18
def secret(self):
print("%s 的年龄是 %d"%(self.name,self.__age))
xiaofang = Women("小芳")
#在对象的方法内部是可以访问私有方法的
xiaofang.secret()
小芳 的年龄是 18
在对象的方法内部是可以访问私有方法的
class Women:
def __init__(self,name):
self.name = name
self.__age = 18
def __secret(self):
print("%s 的年龄是 %d"%(self.name,self.__age))
xiaofang = Women("小芳")
#私有方法同样不可以被调用
xiaofang.__secret()
Traceback (most recent call last):
File “F:/Python编程/练习/test.py”, line 12, in
xiaofang.__secret()
AttributeError: ‘Women’ object has no attribute ‘__secret’
私有方法同样不可以被调用
父类的私有属性和私有方法
1. 子类对象不能在自己的方法内部,直接访问父类的私有属性和私有方法
2. 子类对象可以通过父类的公有方法间接访问到私有属性和私有方法
示例:
· B的对象不能直接访问__num2属性
· B的对象不能在demo方法内访问__num2属性
· B的对象可以在demo方法内,调用父类的test方法
· 父类的test方法内部,能够访问__num2属性和__test方法