2015年1月21日星期三

The Third Week's SLOG

    It's already the third week of this semester and the SLOG starts as usual! Why did I say as usual? I've done this last semester for 165 which was also taught by Danny!
    This semester, in the beginning, we are doing class, which we briefly talked about in 108. This week, we are discussing subclasses.
    We implement a general class, and then use subclasses to implement the different consequences. As Danny did in the lecture, a general class is Shape, functions like draw and get_area are in the class but they cannot be implemented in the general class as they differ in different shapes. What we did in this is: raise NotImplementedError: 'Need a subclass.' Also, using a subclass, the subclass should look like this: class Square(Shape), with the name of the general class in it. And, in the __init__ function of the subclass, we are supposed to call the function __init__ of the general class as we are going to use the functions in the general function.
the codes are:
    def draw(self, t):
        ''' (Shape, Turtle) -> NoneType

        Draw self using t.
        '''
        raise NotImplementedError('Need a subclass')

in the subclass:
from shape import Shape
import turtle

class Square(Shape):
    '''
    Represents geometric square lined up with axes

    position: inherited from Shape
    base: float               --- length of base of this Square
    '''

    def __init__(self, x, y, b):
        Shape.__init__(self, x, y)
        self.base = b
  
As for the  draw and get_area function in the subclass, they are implemented. So when we run the subclass, these functions in the subclass will completely replace the functions in the general class in which we raise an error. But when we run the general class Shape, it will still result in an error as the general class will not be influenced by any change we make in the subclass.

没有评论:

发表评论