12.6 Limitations

Now that you have a better understanding of how inheritance works, let’s try a slightly more difficult test program. LISTING 12.7 contains a simple function called test2 to draw two lines that cross. Once the lines are drawn, the color of the first line is changed to red and the width of the second line is changed to 4. What do you think the final picture will look like?

Image

LISTING 12.7 Drawing two lines that cross

If you think that the result should be two crossing black lines, one of which is thicker than the other, you are correct, as FIGURE 12.7 shows. Why didn’t the call to setColor actually change the color of line1? And why didn’t setWidth change the width of line2? Calling setColor or setWidth modifies only the _ _lineColor or _ _lineWidth instance variables; it does not change the way the line appears on the screen. To change the appearance of the line on the screen, we need to redraw it. Although the obvious fix for this small program is to move the setColor and setWidth calls before the call to draw, that is not an effective general solution.

A Python Turtle Graphics window shows two lines crossing each other, in which one line is a solid thin line and another one is a thick line.

FIGURE 12.7 Testing the shape hierarchy.

© 2001–2019 Python Software Foundation. All Rights Reserved.

Another possible solution is that every time we change the color or thickness of the line, we tell the canvas to draw the line again. This solution can produce unintended consequences, however. For example, we might add one more line to the program in Listing 12.7 to call myCanvas.draw(myLine). Now the line is red, but it is in front of the other line. If we want the black line to be in front of the red line, we need to redraw the black line as well. For a complicated drawing, this can turn into a complicated set of dependencies.

The behavior that we really want can be specified as follows:

  1. If the object is not drawn yet, change the value of the instance variable.

  2. If the object is already visible, change the attribute and redraw all the objects on the screen in the same order as they were originally drawn.

One possible solution to this problem would be to add a call to _draw in the setColor and setWidth methods. However, that creates the same problem with the order of drawing just mentioned. Another problem also arises with this approach: To draw the line, we need a turtle. Recall that the turtle is passed as a parameter to the _draw method. However, when we call the setWidth method, we do not (and should not!) have a reference to a turtle object. A final problem is that requirement 1 stipulates that if the line has not yet been drawn, the only thing that setColor should do is change the value of the color instance variable.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.133.140.79