网站建设方案说明书,上海设计公司排名招聘,wordpress做网站,如何做vip影视网站上文我们介绍了面向对象的基础知识#xff0c;了解了类和对象的联系和语法#xff0c;这次我们就紧接着来介绍面向对象中的私有特点——私有属性和私有方法。
私有属性#xff0c;顾名思义是指不能在类的外部被使用或直接访问的属性。私有属性严格意义上来说并不能算做第三…上文我们介绍了面向对象的基础知识了解了类和对象的联系和语法这次我们就紧接着来介绍面向对象中的私有特点——私有属性和私有方法。
私有属性顾名思义是指不能在类的外部被使用或直接访问的属性。私有属性严格意义上来说并不能算做第三种属性因为它只能通过类属性或是实例初始化方法来定义是类属性和实例属性的特殊分支通常以两个下划线开头它的语法结构如下所示
class Fruit:kind apple__WaterContent 85def __init__(self, name, age):self.name nameself.__age agepear Fruit(梨, 2)print(Fruit.kind)
print(Fruit.__WaterContent)apple
Traceback (most recent call last):File D:\Python.py, line 13, in moduleprint(Fruit.__WaterContent)
AttributeError: type object Fruit has no attribute __WaterContent. Did you mean: _Fruit__WaterContent?
class Fruit:kind apple__WaterContent 85def __init__(self, name, age):self.name nameself.__age agepear Fruit(梨, 2)print(pear.name)
print(pear.__age)Traceback (most recent call last):File D:\Python.py, line 13, in moduleprint(pear.__age)
AttributeError: Fruit object has no attribute __age
梨不过在笔者使用的版本中新增了一个机制按照报错提示输入Fruit._Fruit__WaterContent就可以访问私有类属性同理尽管没有提示也可以仿照类属性输入pear._Fruit__age访问私有实例属性。
class Fruit:kind apple__WaterContent 85def __init__(self, name, age):self.name nameself.__age agepear Fruit(梨, 2)print(Fruit._Fruit__WaterContent)
print(pear._Fruit__age)85
2
除了私有属性类里还有私有方法语法结构与正常方法类似区别是在私有方法前有__作为标识这一特点与私有属性一致需要注意在博客中下划线看起来是一整条而实际上的个数是两个大家将代码复制到自己的编译器中就可以看到了。
class Fruit:kind apple__WaterContent 85def __init__(self, name, age):self.name nameself.__age agedef 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 moduleprint(pear.__object())
AttributeError: Fruit object has no attribute __object
梨
None
私有方法适用于类内部的调用如下所示
class Fruit:kind apple__WaterContent 85def __init__(self, name, age):self.__name nameself.age agedef __addage(self):self.age 1def newage(self):self.__addage()print(self.age)pear Fruit(梨, 2)
print(pear.newage())3
None
类的私有属性和私有方法就介绍到这里今天是大年二十九预祝各位朋友龙年大吉事事如意。