Practical Application of OOP

  • First class constructs the original items provided

  • Second class handles Lists and Strings

  • Third class handles Dictionaries

  • Both second and third class print only the first 3 positions of the given data type

class Shortner:
    def __init__(self, items):
        self.original_items = items

    def print_original_items(self):
        print(self.original_items)

class ListAndCharShortner(Shortner):
    def print_shortend_items(self):
        print(self.original_items[0:3]) # prints the first 3 elements for the original Shortner class

class DictShortner(Shortner):
    def print_shortend_items(self):
        # original_items = {1: 'mike', 2: 'tom', 3: 'rebeca', 4: 'mike', 5: 'paul'}
        dict = self.original_items
        count = 0
        new_dict = {}

        # My Solution:
        # for i in dict.items():
        #     if count < 3:
        #         new_dict[str(i[0])] = i[1]
        #         count += 1

        # Video Solution:
        for (k,v) in dict.items():
            if (count < 3):
                new_dict.update({k: v})
                count += 1

        print(new_dict)


myshortner = ListAndCharShortner("This is a sentence") # This will not work with a dictionary
myshortner.print_shortend_items()

mydict = DictShortner({1: 'mike', 2: 'tom', 3: 'rebeca', 4: 'mike', 5: 'paul'})
mydict.print_shortend_items()

Last updated