Python学习笔记—— 面向对象2. 私有属性和私有方法

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方法

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值