python私有属性和保护属性区别_技巧22-类实例的受保护属性和私有属性.ipynb

本文介绍了Python类的初始化方法`__init__`,私有属性`__age`和受保护属性`_protect_var`的使用。通过示例展示了如何创建对象并访问其属性,以及如何直接修改受保护属性的值。强调了对私有属性的访问限制及其规避方式。
摘要由CSDN通过智能技术生成

{

"cells": [

{

"cell_type": "code",

"execution_count": 13,

"metadata": {},

"outputs": [

{

"name": "stdout",

"output_type": "stream",

"text": [

"My name is Python, I'm 27 years old, protect value=1\n"

]

}

],

"source": [

"class A:\n",

" \n",

" def __init__(self, name, age):\n",

" self.name = name\n",

" self.__age = age\n",

" self._protect_var = 1\n",

" \n",

" def __str__(self):\n",

" return \"My name is {}, I'm {} years old, protect value={}\".format(\n",

" self.name,\n",

" self.__age,\n",

" self._protect_var\n",

" )\n",

"\n",

"a = A(name='Python', age=27)\n",

"print(a)"

]

},

{

"cell_type": "code",

"execution_count": 14,

"metadata": {},

"outputs": [

{

"ename": "AttributeError",

"evalue": "'A' object has no attribute '__age'",

"output_type": "error",

"traceback": [

"\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",

"\u001b[0;31mAttributeError\u001b[0m Traceback (most recent call last)",

"\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m()\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0ma\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0m__age\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m",

"\u001b[0;31mAttributeError\u001b[0m: 'A' object has no attribute '__age'"

]

}

],

"source": [

"a.__age"

]

},

{

"cell_type": "code",

"execution_count": 17,

"metadata": {},

"outputs": [],

"source": [

"a._A__age = 30"

]

},

{

"cell_type": "code",

"execution_count": 18,

"metadata": {},

"outputs": [

{

"name": "stdout",

"output_type": "stream",

"text": [

"My name is Python, I'm 30 years old, protect value=1\n"

]

}

],

"source": [

"print(a)"

]

},

{

"cell_type": "code",

"execution_count": null,

"metadata": {},

"outputs": [],

"source": []

}

],

"metadata": {

"kernelspec": {

"display_name": "Python 3",

"language": "python",

"name": "python3"

},

"language_info": {

"codemirror_mode": {

"name": "ipython",

"version": 3

},

"file_extension": ".py",

"mimetype": "text/x-python",

"name": "python",

"nbconvert_exporter": "python",

"pygments_lexer": "ipython3",

"version": "3.7.0"

}

},

"nbformat": 4,

"nbformat_minor": 2

}

一键复制

编辑

Web IDE

原始数据

按行查看

历史

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值