I have a class of boxes that need to move around in a grid, but need to access that grid's coordinates in its methods. I don't want my classes to inherit the grid unless they need to. Do I need to pass the grid to the classes as a param开发者_运维问答eter, or make the box classes inherit from the grid class? Thanks.
This is the edit. Let me clarify. The classes of boxes need to know the length and width of the grid. Therefore, I need to call inside the class functions like Grid.length() and stuff. I need it though, to give me the length and width of the grid that was created.
General rule would be parameter.
The question is is-a vs. has-a:
Is the box a grid?
yes: # if so, then is it really a box???
The box should inherit grid
no:
The box should get a reference to the grid
#(generally through a setter or constructor parameter).
Edit
An example:
class Grid:
def __init__(self,width=1,height=1):
this.width = width; this.height = height;
def getDimensions(self):
return (this.width, this.height)
class Box:
def __init__(self, grid):
this.__grid = grid; this.x = 0; this.y = 0
def verify(self):
width, height = this.__grid.dimensions()
if this.x < width and this.y < height:
print( "A-OK!" );
else
print( "I am off the grid!!!" )
grid = Grid();
box = Box(grid);
box.verify();
The box should reference to the grid. However, with inner classes, you don't need to pass the grid as a parameter, with inner classes. Inner classes is a Java feature, but you can metaprogram it to Python.
http://tomayko.com/writings/python-inner-classes
What is the purpose of python's inner classes?
Since a box is not a refinement of a type of grid you should not inherit them.
You may be interested in the Acquisition pattern and module. This allows getting attributes from the dynamic containment hierarchy, rather than static class (is-a) hierarchy.
From what you have said, box
classes should not inherit from the grid
class as this would violate the LSP.
See: What is the Liskov Substitution Principle?
The box
classes should know how to query the grid
for relevant information.
精彩评论