Python入门知识点分享——(十九)私有属性和方法

上文我们介绍了面向对象的基础知识,了解了类和对象的联系和语法,这次我们就紧接着来介绍面向对象中的私有特点——私有属性和私有方法。

私有属性,顾名思义是指不能在类的外部被使用或直接访问的属性。私有属性严格意义上来说并不能算做第三种属性,因为它只能通过类属性或是实例初始化方法来定义,是类属性和实例属性的特殊分支,通常以两个下划线开头,它的语法结构如下所示:

class Fruit:
    kind = 'apple'
    __WaterContent = 85


    def __init__(self, name, age):
        self.name = name
        self.__age = age

pear = Fruit('梨', 2)

print(Fruit.kind)
print(Fruit.__WaterContent)
apple
Traceback (most recent call last):
  File "D:\Python.py", line 13, in <module>
    print(Fruit.__WaterContent)
AttributeError: type object 'Fruit' has no attribute '__WaterContent'. Did you mean: '_Fruit__WaterContent'?
class Fruit:
    kind = 'apple'
    __WaterContent = 85


    def __init__(self, name, age):
        self.name = name
        self.__age = age

pear = Fruit('梨', 2)

print(pear.name)
print(pear.__age)
Traceback (most recent call last):
  File "D:\Python.py", line 13, in <module>
    print(pear.__age)
AttributeError: 'Fruit' object has no attribute '__age'
梨

不过在笔者使用的版本中新增了一个机制,按照报错提示输入Fruit._Fruit__WaterContent就可以访问私有类属性,同理,尽管没有提示,也可以仿照类属性输入pear._Fruit__age访问私有实例属性。

class Fruit:
    kind = 'apple'
    __WaterContent = 85


    def __init__(self, name, age):
        self.name = name
        self.__age = age

pear = Fruit('梨', 2)

print(Fruit._Fruit__WaterContent)
print(pear._Fruit__age)
85
2

除了私有属性,类里还有私有方法,语法结构与正常方法类似,区别是在私有方法前有__作为标识,这一特点与私有属性一致,需要注意在博客中下划线看起来是一整条,而实际上的个数是两个,大家将代码复制到自己的编译器中就可以看到了。

class Fruit:
    kind = 'apple'
    __WaterContent = 85

    def __init__(self, name, age):
        self.name = name
        self.__age = age

    def newname(self):
        print(self.name)

    def __object(self):
        print("生成了新对象")

pear = Fruit('梨', 2)
print(pear.newname())
print(pear.__object())
Traceback (most recent call last):
  File "D:\Python.py", line 17, in <module>
    print(pear.__object())
AttributeError: 'Fruit' object has no attribute '__object'
梨
None

私有方法适用于类内部的调用,如下所示

class Fruit:
    kind = 'apple'
    __WaterContent = 85

    def __init__(self, name, age):
        self.__name = name
        self.age = age

    def __addage(self):
        self.age += 1

    def newage(self):
        self.__addage()
        print(self.age)

pear = Fruit('梨', 2)
print(pear.newage())
3
None

类的私有属性和私有方法就介绍到这里,今天是大年二十九,预祝各位朋友龙年大吉,事事如意。

  • 8
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值