-
封装
-
继承
-
多态
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
|
class
c1:
def
__init__(
self
,name,obj):
self
.name
=
name
self
.obj
=
obj
class
c2:
def
__init__(
self
,name,age):
self
.name
=
name
self
.age
=
age
def
show(
self
):
print
(
self
.name)
return
123
class
c3:
def
__init__(
self
, a1):
self
.money
=
123
self
.aaa
=
a1
c2_obj
=
c2(
'aa'
,
11
)
# c2_obj是c2类型
# - name = "aa"
# - age = 11
c1_obj
=
c1(
"alex"
, c2_obj)
# c1_obj 是c1 类型
# - name = "alex"
# - obj = c2_obj
c3_obj
=
c3(c1_obj)
# 使用c3_obj执行show方法
ret
=
c3_obj.aaa.obj.show()
print
(ret)
print
(c3_obj.money)
-
-
-
-
-
-
-
-
-
aa
123
123
|
-
我定义了3个类,每个类都有自己的构造方法__init__,我对每一个类都进行实例化一个对象;每个对象创建的时候会自动调用自己的__init__方法封装不同的内容;
-
self是一个形式参数,他就相当于实例,比如当c1_obj=c1('alex',c2_obj),self就等于c1_obj
-
当我们输出money这个字段的时候,c3_obj可以调用show这个方法输出money(间接调用self)或者直接输出c3_obj.money(直接调用)
-
对象本身也可以当做参数传给其他的类
1
2
3
4
5
6
7
8
|
class
Foo:
def
__init__(
self
, name):
self
.name
=
name
def
show(
self
):
print
(
self
.name)
import
pickle
obj
=
Foo(
'alex'
)
pickle.dump(obj,
open
(
'db'
,
'wb'
))
|
1
2
3
4
5
6
|
import
pickle
from
s1
import
Foo
ret
=
pickle.load(
open
(
'db'
,
'rb'
))
print
(ret)
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
<s1.Foo
object
at
0x000001E5F421BEB8
>
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
class
F1:
# 父类,基类
def
show(
self
):
print
(
'show'
)
def
foo(
self
):
print
(
self
.name)
class
F2(F1):
# 子类,派生类
def
__init__(
self
, name):
self
.name
=
name
def
bar(
self
):
print
(
'bar'
)
def
show(
self
):
print
(
'F2.show'
)
obj
=
F2(
'alex'
)
obj.show()
obj.foo()
-
-
-
-
-
-
-
-
-
F2.show
alex
|
-
F2是F1的子类
-
创建obj对象的时候,他自动调用F2的构造函数,当他尝试调用foo()方法的时候,首先看自己有没有,如果没有就去父类寻找。类似的,当调用show()的时候,因为自己已经有了,因此直接调用自己的
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
class
S1:
def
F1(
self
):
self
.F2()
def
F2(
self
):
print
(
"S1.f2"
)
class
S2(S1):
def
F3(
self
):
self
.F1()
def
F2(
self
):
print
(
"S2.f2"
)
obj
=
S2()
obj.F3()
obj
=
S1()
obj.F1()
-
-
-
-
-
-
-
-
-
-
-
-
-
S2.f2
S1.f2
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
class
C_2:
def
f2(
self
):
print
(
'C-2'
)
class
C_1(C_2):
def
f12(
self
):
print
(
'C-1'
)
class
C0(C_2):
def
f2(
self
):
print
(
'C0'
)
class
C1(C0):
def
f1(
self
):
print
(
'C1'
)
class
C2(C_1):
def
f12(
self
):
print
(
'C2'
)
class
C3(C1,C2):
def
f3(
self
):
pass
obj
=
C3()
obj.f2()
-
-
-
-
-
C0
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
class
F1:
pass
class
S1(F1):
def
show(
self
):
print
(
'S1.show'
)
class
S2(F1):
def
show(
self
):
print
(
'S2.show'
)
def
Func(obj):
print
(obj.show())
s1_obj
=
S1()
Func(s1_obj)
s2_obj
=
S2()
Func(s2_obj)
-
-
-
-
-
-
-
-
-
-
-
-
-
S1.show
None
S2.show
None
|