use python (jupitor notebook)
Create a EmployeeD class which is a subclass of UserDictand overrides __getitem__ and __setitem__ methods. Then read from your provided file to create a sequence of EmployeeD instancesusing generatorfunctionand printthe total salaries.
please add the running results.
{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "### Python OOP ", "- https://www.tutorialspoint.com/python/python_classes_objects.htm" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Name : Zara, Salary: 2000, Age: 21 ", "Name : Manni, Salary: 5000, Age: 25 ", "Total Employee: 2 ", "Does employee has age attribute? False ", "Employee.__doc__: Common base class for all employees ", "Employee.__name__: Employee ", "Employee.__module__: __main__ ", "Employee.__bases__: (,) ", "Employee.__dict__: {'__module__': '__main__', '__doc__': 'Common base class for all employees', 'empCount': 2, '__init__': , 'displayCount': , 'displayEmployee': , '__dict__': , '__weakref__': } " ] } ], "source": [ "class Employee: #same as Employee(object) ", " 'Common base class for all employees' ", " empCount = 0 #class attribute ", " ", " #name, salary and _age are instance attributes ", " def __init__(self, name, salary, age): #initializer must have at least argument beside self ", " self.name = name ", " self.salary = salary ", " self.__age = age ", " Employee.empCount += 1 ", " ", " def displayCount(self): ", " print(\"Total Employee: {0}\".format(Employee.empCount)) ", " ", " def displayEmployee(self): ", " print(\"Name : {0}, Salary: {1}, Age: {2}\".format(self.name,self.salary, self.__age)) ", " ", "\"This would create first object of Employee class\" ", "emp1 = Employee(\"Zara\", 2000, 21) ", "\"This would create second object of Employee class\" ", "emp2 = Employee(\"Manni\", 5000, 25) ", "emp1.displayEmployee() ", "emp2.displayEmployee() ", "print(\"Total Employee: {0}\".format(Employee.empCount)) ", "print(\"Does employee has age attribute? \", hasattr(emp1, 'age')) # Returns true if 'age' attribute exists ", "print(\"Employee.__doc__:\", Employee.__doc__) #Class documentation string or none, if undefined ", "print(\"Employee.__name__:\", Employee.__name__) #Class name ", "print(\"Employee.__module__:\", Employee.__module__) #Module name in which the class is defined ", "print(\"Employee.__bases__:\", Employee.__bases__) #A possibly empty tuple containing the base classes, in the order of their occurrence in the base class list ", "print(\"Employee.__dict__:\", Employee.__dict__) #Dictionary containing the class's namespace ", "#print(emp1.name) #name is accessible ", "#print(emp1.__age) #__age is hidden, an attribute with double underscore means it is hidden outside of the class" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Calling commissionemployee constructor ", "Name : Holly, Salary: 2500, Age: 30 ", "Total Employee: 3 ", "True " ] } ], "source": [ "\"\"\" ", "inheritance ", "\"\"\" ", "class CommissionEmployee(Employee): # define child class ", " def __init__(self, name, salary, age, commissionrate): ", " Employee.__init__(self, name, salary, age) #use super class's name to access base class ", " self.__commissionrate = commissionrate ", " print(\"Calling commissionemployee constructor\") ", " ", " def getCommission(self): ", " return self.__commissionrate * self.salary ", " ", "c1 = CommissionEmployee(\"Holly\", 2500, 30, 0.5) ", "c1.displayEmployee() ", "c1.displayCount() ", "c1.getCommission() ", "print(isinstance(c1, Employee)) #determine if an instance is also an instance of a parent class" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Python subclass collections" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[Event]: login ", "user = [Event]: user ", "event_type = [Event]: login ", "date = [Event]: 2017-07-11 " ] } ], "source": [ "#class Event(dict):#needs to override every single method in dict to be customized ", "# def __getitem__(self, key): ", "# value = super().__getitem__(key) ", "# return f\"[{self.__class__.__name__}]: {value}\" ", " ", "from collections import UserDict ", "class Event(UserDict): ", " def __getitem__(self, key): ", " value = super().__getitem__(key) ", " return f\"[{self.__class__.__name__}]: {value}\" ", " ", "event = Event(user=\"user\", event_type=\"login\", date=\"2017-07-11\") ", "print(event['event_type']) #print(event.__getitem__('event_type')) ", "for key, value in event.items(): ", " print(f\"{key} = {value}\") #the items() method doesnt call the Event's __getitem__() " ] }, { "cell_type": "code", "execution_count": 10, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[Event]: 2017-07-11 - [Event]: login " ] } ], "source": [ "def log_event_type(event_type, date, **args): #first and second parameters are keywords from a dictionary ", " print(f\"{date} - {event_type}\") ", " ", "log_event_type(**event) " ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "jsmith ", "jsmith ", "93 njohnson Nathan Johnson " ] } ], "source": [ "import collections ", "UserRecord = collections.namedtuple(\"UserRecord\", ('user_id', 'username', 'first_name', 'last_name')) ", "ur1 = UserRecord(92, 'jsmith', 'John', 'Smith') ", "ur2 = UserRecord(93, 'njohnson', 'Nathan', 'Johnson') ", "print(ur1[1]) #access by index like regular tuple ", "print(ur1.username) #access by identifier ", "print(*ur2) #unpacking" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "create a new dictionary by concatenating many with the syntax new_dict = {**d1, **d2} ", " ", "If we change one of the source dictionaries, these wont be reflected on the new dictionary ", " ", "with a ChainMap, this would be reflected. ", " ", "Whenever we use collections, be careful about the methods/operators that if they return a new collection or if they operate on the original collection" ] }, { "cell_type": "code", "execution_count": 14, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{'date': '2017-07-11', ", " 'event_type': 'login', ", " 'user': 'user', ", " 'system': 'PROD1', ", " 'status': 'up'}" ] }, "execution_count": 14, "metadata": {}, "output_type": "execute_result" } ], "source": [ "context = {\"system\": \"PROD1\", \"status\": \"up\"} ", "event = {'date': '2017-07-11', 'event_type': 'login', 'user': 'user'} ", "enriched_event = {**event, **context} ", "context[\"system\"] = \"system changed\" ", "enriched_event" ] }, { "cell_type": "code", "execution_count": 16, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{'system': 'PROD2', 'status': 'up'}" ] }, "execution_count": 16, "metadata": {}, "output_type": "execute_result" } ], "source": [ "enriched_event = collections.ChainMap(event, context) ", "enriched_event['system'] # PROD1 ", "context['system'] = \"PROD2\" ", "enriched_event['system'] # PROD2 ", "# it also works the other way around ", "enriched_event['user'] = 'another_user' ", "event['user'] # another_user ", "context" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.7.0" } }, "nbformat": 4, "nbformat_minor": 2 }