I have a class that creates blocks in a 2d board. I defined it so it does so given their height, length and location on the board but also made an alternative constructor to create blocks by passing its coordinates in the board.
class Block:
""" Create a block of given height and length in a starting location."""
def __init__(self, name: str, h: int, l: int, location: Tuple[int,int]):
self.name = name
self.coords = [tuple_sum(t1=location, t2=(i//l , i%l)) for i in range(h*l)]
# tuple_sum does (a, b)+(c, d) -> (a+c, b+d)
@classmethod
def from_coords(cls, name: str, coords: List[Tuple]):
block = cls.__new__(cls)
block.name = name
block.coords = coords
return block
...
def __str__(self) -> str:
return f'Name: {self.name}\nCoords: {self.coords}'
I'm trying to create a child class for the blank spaces in the board. I thought that using the from_coords constructor would do everything but for some reason I don't understand the created elements are not initialized, i.e don't have name or coords attributes.
class SpacesBlock(Block):
""" Make a block of spaces from a list of coordenates """
def __init__(self, coords):
super().from_coords(" ",coords)
...
spaces = SpacesBlock([(0,0),(0,1)])
print(spaces)
AttributeError Traceback (most recent call last)
\block.py in <module>
space = SpacesBlock([(0,0),(0,1)])
----> print(spaces)
AttributeError: 'SpacesBlock' object has no attribute 'name'
I thought it was the from_coords constructor but it works fine
a = Block.from_coords("A",[(0,0),(1,0)])
print(a)
Name: A
Coords: [(0, 0), (1, 0)]
I know I can just define the name and coords in the init of SpacesBlock and everything is fine but I am very curious about why it doesn't work as I thought it would. What am I missing?