一、面向对象三大特征
封装继承多态
重载重写
class allStr():
'''
父类
'''
all_worlds
= 'helle python'
other_world
= "人生苦短,我学Python"
def all_print(self
):
'''打印其他的话'''
print(self
.other_world
)
class myStr(allStr
):
'''子类'''
def my_print(self
):
'''打印我的话'''
print(allStr
.all_worlds
)
my_str
= myStr
()
my_str
.my_print
()
my_str
.all_print
()
my_str
.all_worlds
= '哈哈哈哈啊哈'
my_str
.my_print
()
helle python
人生苦短,我学Python
helle python
class ALLStr:
all_words
= "你好,syd"
my_worlds
= "哈哈哈"
def print_str(self
):
print(self
.all_words
)
class MyStr(ALLStr
):
"""子类"""
def print_str(self
):
"""重写父类方法"""
print("不太好!")
def print_me(self
):
"""属于自己的方法"""
print("人生苦短,我学Python!")
def print_me(self
, your_worlds
):
"""重载自己的类方法"""
print(your_worlds
)
my_str
= MyStr
()
my_str
.print_str
()
your_worlds
= "hahah"
my_str
.print_me
(your_worlds
)
不太好!
hahah
二、生命游戏
"""
二维矩阵类
"""
class Matrix2D:
"""通用的二维矩阵类"""
def __init__(self
, rows
, cols
):
"""初始化矩阵row行,col列"""
self
.grid
= [[0]*cols
for _
in range(rows
)]
self
.rows
= rows
self
.cols
= cols
def get_cell(self
, r
, c
):
"""获取单元格(r,c)的值"""
return self
.grid
[r
][c
]
def set_cell(self
, n
, *args
):
"""设置某个位置的值"""
for r
, c
in args
:
self
.grid
[r
][c
] = n
def inc_cells(self
, *args
):
"""将任意单元格 +1 """
for r
, c
in args
:
self
.grid
[r
][c
] += 1
def set_all_cells(self
, n
=0):
"""将所有单元格值都设为 n """
for i
in range(self
.rows
):
for j
in range(self
.cols
):
self
.grid
[i
][j
] = n
"""
生命游戏
"""
from matrix2d
import Matrix2D
rows
= 5
cols
= 5
life_mat
= Matrix2D
(rows
,cols
)
nc_mat
= Matrix2D
(rows
,cols
)
life_mat
.set_cell
(1, (1,3), (2,1), (2,3), (3,2), (3,3))
border_str
= ' _ ' * cols
def get_mat_str(a_mat
):
"""处理打印字符串"""
disp_str
= ''
for i
in range(rows
):
lst
= [get_chr
(a_mat
,i
,j
) for j
in range(cols
)]
disp_str
+= ''.join
(lst
) + '\n'
return disp_str
def get_chr(a_mat
, r
, c
):
"""设置图符号"""
return ' 1 ' if a_mat
.get_cell
(r
,c
) > 0 else ' 0 '
def do_generation():
"""打印当前状态并生成下个状态"""
print(border_str
+ '\n' + get_mat_str
(life_mat
))
nc_mat
.set_all_cells
(0)
for i
in range(rows
):
for j
in range(cols
):
if life_mat
.get_cell
(i
, j
):
im
= (i
- 1) % rows
ip
= (i
+ 1) % rows
jm
= (j
- 1) % cols
jp
= (j
+ 1) % cols
nc_mat
.inc_cells
((im
, jm
), (im
, j
),(im
,jp
),(i
,jm
),(i
,jp
),(ip
,jm
),(ip
,j
),(ip
,jp
))
for i
in range(rows
):
for j
in range(cols
):
n
= nc_mat
.get_cell
(i
, j
)
if n
< 2 or n
> 3:
life_mat
.set_cell
(0,(i
, j
))
elif n
== 3:
life_mat
.set_cell
(1,(i
, j
))
import time
n
= 100
for i
in range(n
):
do_generation
()
time
.sleep
(1)
---------------------------------------------------------------------------
ModuleNotFoundError Traceback (most recent call last)
<ipython-input-16-d18dab4842fa> in <module>
4 # 文件名mian.py
5
----> 6 from matrix2d import Matrix2D
7
8 rows = 5
ModuleNotFoundError: No module named 'matrix2d'
三、装饰器