b站达内python课学习笔记
P116 Python面向对象–3.1 课程回顾
一、day10复习
"""
day10 复习
类和对象
类:抽象 向量 class Vector2 str int list
对象:具体 1,2 Vector2(1,2) "a" 1 [1,2]
之间的区别:类与类行为不同
对象与对象数据不同
Vector2(1,2) Vector2(3,4)
同一个类型的多个对象,数据不同(1,2/3,4),行为(求方向,求大小)相同.
类成员:
实例:对象的数据(变量),对象的行为(方法).
类:类的数据(变量),类的行为(方法).
可以被所有对象共同操作的数据
静态方法:
实例方法操作实例变量,表示"个体"行为.
类方法操作类变量,表示"大家"行为.
静态方法不能操作数据,表示为函数都可以.
"""
二、示例代码
访问实例变量和实例方法
class MyClass:
def __init__(self, a):
self.a = a
def print_self(self):
print(self.a)
m01 = MyClass(100)
m01.b = 1
m02 = MyClass(100)
print(m02.b)
print(m02.a)
访问类变量和类方法
class MyClass02:
a = 0
@classmethod
def print_self(cls):
print(cls.a)
print(MyClass02.a)
MyClass02.print_self()
不常见不建议用的访问方式
MyClass.print_self(m01)
m03 = MyClass02()
print(m03.a)
print(m03.print_self())
P117 Python面向对象–3.2 课后作业解析
一、练习1
"""
[
["00", "01", "02", "03"],
["10", "11", "12", "13"],
["20", "21", "22", "23"],
]
在二维列表中,获取13位置,向左,3个元素
在二维列表中,获取22位置,向上,2个元素
在二维列表中,获取03位置,向下,2个元素
"""
class Vector2:
"""
二维向量
可以表示位置/方向
"""
def __init__(self, x, y):
self.x = x
self.y = y
@staticmethod
def left():
return Vector2(0, -1)
@staticmethod
def right():
return Vector2(0, 1)
@staticmethod
def up():
return Vector2(-1, 0)
@staticmethod
def down():
return Vector2(1, 0)
class DoubleListHelper:
@staticmethod
def get_elements(target, vect_pos, vect_dir, count):
"""
在二维列表中获取指定位置,指定方向,指定数量的元素.
:param target: 二维列表
:param vect_pos: 指定位置
:param vect_dir: 指定方向
:param count: 指定数量
:return: 列表
"""
list_result = []
for i in range(count):
vect_pos.x += vect_dir.x
vect_pos.y += vect_dir.y
element = target[vect_pos.x][vect_pos.y]
list_result.append(element)
return list_result
list01 = [
["00", "01", "02", "03"],
["10", "11", "12", "13"],
["20", "21", "22", "23"],
]
re = DoubleListHelper.get_elements(list01, Vector2(1, 3), Vector2.left(), 3)
for item in re:
print(item)
re = DoubleListHelper.get_elements(list01, Vector2(2, 2), Vector2.up(),