The point of 12.inheritance syntax


#1



Hello everyone! I am not stuck with this exercise, but I just don't see the point of it. Following the instruction, I created a Triangle class, which is a inheritance of Shape class. Then both class have init method, I don't see where is the magic of inheritance. I mean I don't understand the point of the instruction and I think maybe I missed something? Thx!


class Shape(object):
    """Makes shapes!"""
    def __init__(self, number_of_sides):
        self.number_of_sides = number_of_sides

# Add your Triangle class below!
class Triangle(Shape):
    def __init__(self, side1, side2, side3):
        self.side1 = side1
        self.side2 = side2
        self.side3 = side3


#2

Here's a better example

class Defaultdict(dict):
    def __init__(self, default_factory):
        super(Defaultdict, self).__init__()
        self._default_factory = default_factory

    def __getitem__(self, key):
        if self.has_key(key):
            return super(Defaultdict, self).__getitem__(key)
        return self._default_factory(key)


mydict = Defaultdict(lambda x: x + 1)
mydict[3] = 'three'
print mydict[3]  # three
print mydict[4]  # 5
print mydict[5]  # 6
print mydict[6]  # 7
print mydict[7]  # 8

This is similar to the defaultdict class in the collections module, however, this version gives the default_factory the key, while the one in the standard library does not get to see the key


#3

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.