【发布时间】:2018-06-03 12:18:38
【问题描述】:
我认为我误用了子类的概念。我正在使用 Grids 和 Cells 开展一个爱好项目。
我所拥有的是 Cell 类及其子类 HexCell 的实现,它基本上重新定义了许多属性/方法,如下所示:
class Cell:
def __init__(self, row_loc, col_loc):
self.row = row_loc
self.col = col_loc
self.links = set()
self.neighbors = 4*[None]
def __repr__(self):
return f'Cell @({self.row},{self.col})'
def link(self, other, bidir = True):
self.links.add(other)
if bidir: other.links.add(self)
然后我有一个子类HexGrid,它遵循类似的结构和新参数。
class HexCell(Cell):
def __init__(self, r_out, th_around):
# I'm indexing Hex cells around a center cell
# instead of by rows and columns; Prefixed hex
# as they follow the hexagon, and not regular polar coordinates.
self.hex_r = r_out
self.hex_th = th_around
self.neighbors = 6*[None]
self.links = set()
def __repr__(self):
return f"HexCell @[{self.hex_r}, {self.hex_th}]"
def bind(self, other, to_dir):
to_dir = to_dir % 6
if (self.neighbors[to_dir] is None):
self.neighbors[to_dir] = other
other.neighbors[to_dir - 3] = self
# Hexagonal grids share neighbors.
other_1 = other.neighbors[to_dir - 2]
if (self.neighbors[to_dir - 1] is None) & (other_1 is not None):
self.bind(other_1, to_dir - 1)
other_5 = other.neighbors[to_dir - 4]
if (self.neighbors[to_dir - 5] is None) & (other_5 is not None):
self.bind(other_5, to_dir - 5)
在这种情况下,方法self.link(other) 是共享的,但其他属性从矩形网格变为六边形,例如从(row, col) 到(hex_r, hex_th) 的位置,或者neighbors 作为4 列表或6 列表。因此,我希望这些属性依赖于另一个单元类型属性并转移到子类。
【问题讨论】:
-
这打破了里氏替换原则;
HexCell声称是Cell的子类,但它不共享相同的公共属性,并且对于相同的行为似乎有不同的方法。