mirror of
https://github.com/apachecn/ailearning.git
synced 2026-02-09 13:25:39 +08:00
71 lines
1011 B
Markdown
71 lines
1011 B
Markdown
# 共有,私有和特殊方法和属性
|
||
|
||
* 我们之前已经见过 `special` 方法和属性,即以 `__` 开头和结尾的方法和属性
|
||
* 私有方法和属性,以 `_` 开头,不过不是真正私有,而是可以调用的,但是不会被代码自动完成所记录(即 Tab 键之后不会显示)
|
||
* 其他都是共有的方法和属性
|
||
* 以 `__` 开头不以 `__` 结尾的属性是更加特殊的方法,调用方式也不同:
|
||
|
||
In [1]:
|
||
|
||
```py
|
||
class MyClass(object):
|
||
def __init__(self):
|
||
print "I'm special!"
|
||
def _private(self):
|
||
print "I'm private!"
|
||
def public(self):
|
||
print "I'm public!"
|
||
def __really_special(self):
|
||
print "I'm really special!"
|
||
|
||
```
|
||
|
||
In [2]:
|
||
|
||
```py
|
||
m = MyClass()
|
||
|
||
```
|
||
|
||
```py
|
||
I'm special!
|
||
|
||
```
|
||
|
||
In [3]:
|
||
|
||
```py
|
||
m.public()
|
||
|
||
```
|
||
|
||
```py
|
||
I'm public!
|
||
|
||
```
|
||
|
||
In [4]:
|
||
|
||
```py
|
||
m._private()
|
||
|
||
```
|
||
|
||
```py
|
||
I'm private!
|
||
|
||
```
|
||
|
||
注意调用方式:
|
||
|
||
In [5]:
|
||
|
||
```py
|
||
m._MyClass__really_special()
|
||
|
||
```
|
||
|
||
```py
|
||
I'm really special!
|
||
|
||
``` |