Exercise: Subclassing int

Alright, time to subclass int.
Make a class named Double that extends int. Now override new. Create a new int instance from whatever is passed in as arguments and keyword arguments. Return that instance. And, finally, double (multiply by two) the int that you created in new. Return the new, doubled value. For example, Double(5) would return a 10.

class Double(int):
    def __new__(*args, **kwargs):
        self = int.__new__(*args, **kwargs)
        self = self * 2
        return self

Exercise: Subclassing list

Now I want you to make a subclass of list. Name it Liar.
Override the len method so that it always returns the wrong number of items in the list. For example, if a list has 5 members, the Liar class might say it has 8 or 2.

class Liar(list):
    def __len__(self):
        value = super().__len__()
        return value + 100

Exercise: Using @classmethod

Let’s practice using @classmethod! Create a class method in Letter named from_string that takes a string like “dash-dot” and creates an instance with the correct pattern ([’_’, ‘.’]).

class Letter:
    def __init__(self, pattern=None):
        self.pattern = pattern
      
    def __iter__(self):
        yield from self.pattern
      
    def __str__(self):
        output = []
        for blip in self:
            if blip == '.':
                output.append('dot')
            else:
                output.append('dash')
        return '-'.join(output)
    
    @classmethod
    def from_string(cls, str_pattern):
        list_pattern = [] 
        
        for item in str_pattern.split('-'):
            if item == "dot":
                list_pattern.append('.')
            else:
                list_pattern.append('_')
        return cls(list_pattern)
    

class S(Letter):
    def __init__(self):
         pattern = ['.', '.', '.']
         super().__init__(pattern)