Python面向对象编程:概念、实践与项目
1. Python中的私有属性与哲学
1.1 私有属性的实现与访问
在Python中,我们可以通过在属性名前添加双下划线来表示该属性为私有属性。以下是一个示例代码:
In [1]: inst1 = NewClass(name='Monty', attribute='Python')
In [2]: print(inst1)
Monty has attribute Python
In [3]: print(inst1.name)
Monty
In [4]: print(inst1.attribute)
Traceback (most recent call last):
File "<pyshell#3>", line 1, in <module>
print(inst1.attribute)
AttributeError: 'newClass' object has no attribute 'attribute'
In [5]: dir(inst1)
Out [5]: ['NewClass__attribute', '__class__', ... , 'name']
In [6]: print(inst1.NewClass__attribute)
Python
在 __init__ 方法中,我们定义了两个属性: name 和 attribute 。当我们在 attribute
Python面向对象编程实战指南
超级会员免费看
订阅专栏 解锁全文

被折叠的 条评论
为什么被折叠?



