python3面向对象(3)私有属性和方法以及访问私有属性和方法的方式

python3中的私有属性和方法是以__两个下划线开头的:

class People():#定义一个类
    def __init__(self, name, age):
        self.name = name#公有属性
        self.__age = age#私有属性

    def __money(self):#私有方法
        print('我不告诉你我多少岁')



p = People('小华', 'xx')
print(p.name)#小华
# print(p.__age)#AttributeError: 'People' object has no attribute '__age'
# p.__money()#AttributeError: 'People' object has no attribute '__money'

 

第一种访问:访问私有属性和方法的方式(在类内,普通方法可以访问私有属性和方法,然后再调用普通方法来访问私有的):

class People():#定义一个类
    def __init__(self, name, age):
        self.name = name#公有属性
        self.__age = age#私有属性

    def __money(self):#私有方法
        print('我不告诉你我多少岁')

    #定义一个普通方法来访问私有方法
    def get_money(self):
        self.__money()

    ##定义一个普通方法来访问私有属性
    def get_age(self):
        print(self.__age)


p = People('小华', 'xx')
print(p.name)#小华
# print(p.__age)#AttributeError: 'People' object has no attribute '__age'
# p.__money()#AttributeError: 'People' object has no attribute '__money'
p.get_age()#xx
p.get_money()#我不告诉你我多少岁

 第二种访问:访问私有属性和方法的方式(通过_类名__私有(属性或方法))

class People():#定义一个类
    def __init__(self, name, age):
        self.name = name#公有属性
        self.__age = age#私有属性

    def __money(self):#私有方法
        print('我不告诉你我多少岁')

    #定义一个普通方法来访问私有方法
    def get_money(self):
        self.__money()

    ##定义一个普通方法来访问私有属性
    def get_age(self):
        print(self.__age)


p = People('小华', 'xx')
print(p.name)#小华
# print(p.__age)#AttributeError: 'People' object has no attribute '__age'
# p.__money()#AttributeError: 'People' object has no attribute '__money'
p.get_age()#xx
p.get_money()#我不告诉你我多少岁
#使用实例对象._类名__属性/方法名的方式来访问私有属性或私有方法。
print(p._People__age)#xx
p._People__money()#我不告诉你我多少岁

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值