Question

In: Computer Science

PHYTON QUESTIONS Your assignment is to write the following magic methods for the Date class. 1....

PHYTON QUESTIONS

Your assignment is to write the following magic methods for the Date class.

1. __eq__ returns True if two Date objects have the same month, day, and year.

2. __add__ is passed an int as a parameter, and adds that number of days to the Date. It is nondestructive. For example:

>>> d = Date(1,31,2017)

>>> d + 5 Date(2,5,2017)

>>> d Date(1,31,2017)

3. __getitem__ is passed either an int between 0 and 2, or a str ‘month’, ‘day’, or ‘year’. It returns the appropriate instance variable from the Date object, or raises an exception otherwise. For example:

>>> d = Date(2,1,2017)

>>> d[0] 2

>>> d[2] 2017

>>> d[‘day’] 1

>>> d[4] # should raise an IndexError

4. __setitem__ is passed an index (as described in problem 4) and an integer, and sets the month, day, or year of the Date object to be that integer. If the index is not of the correct type or value, then an exception is raised. For example:

>>> d = Date(2,1,2017)

>>> d[0] = 5

>>> d Date(5,1,2017)

>>> d[‘year’] = 2020

>>> d Date(5,1,2020)

>>> d[‘moth’] = 31 # should raise an IndexError

5. __radd__ is passed an integer, and modifies the Date object to be the specified number of days into the future. It is destructive. For example:

>>> d = Date(2,1,2017)

>>> d += 28

>>> d Date(3,1,2017)

Solutions

Expert Solution

import datetime
class Date:
  
def __init__(self, mm, dd, yy):
    self.dateObj = datetime.date(yy, mm, dd)

def __eq__(self, date2):
    if (self.dateObj == date2.dateObj) :
      test = 1
    else:
      test = 0
      return bool(test)
    
def __add__(self, d):
    newDate = self.dateObj + datetime.timedelta(days=d)
    return (str(newDate.month) + "/" + str(newDate.day) + "/" + str(newDate.year))

def __getitem__(self, item):
      if (item==0) or (item=='month'):
        return self.dateObj.month
      elif (item==1) or (item=='day'):
        return self.dateObj.day
      elif (item==2) or (item=='year'):
        return self.dateObj.year
      else:
        raise IndexError("Item passed is not valid")

def __setitem__(self, index, value):
    try:
      if (index==0) or (index=='month'):
        self.dateObj = self.dateObj.replace(month=value)
      elif (index==1) or (index=='day'):
        self.dateObj = self.dateObj.replace(day=value)
      elif (index==2) or (index=='year'):
        self.dateObj = self.dateObj.replace(year=value)
      else:
        raise IndexError("Invalid Index")
    except ValueError:
        raise IndexError("Invalid Value")

def __radd__(self, value):
    self.dateObj = self.dateObj + datetime.timedelta(days=value)
    return str(self.dateObj.month) + "/" + str(self.dateObj.day) + "/" + str(self.dateObj.year)


Related Solutions

Write a Java code to represent a 1. Date class. As date class is composed of...
Write a Java code to represent a 1. Date class. As date class is composed of three attributes, namely month, year and day; so the class contains three Data Members, and one method called displayDate() which will print these data members. Test the Date class using main class named DateDemo. Create two objects of date class. Initialize the data fields in Date class using the objects, invoke the method displyaDate(). Date month : String year: int day : int displayDate():...
The assignment is to write a class called data. A Date object is intented to represent...
The assignment is to write a class called data. A Date object is intented to represent a particuar date's month, day and year. It should be represented as an int. -- write a method called earlier_date. The method should return True or False, depending on whether or not one date is earlier than another. Keep in mind that a method is called using the "dot" syntax. Therefore, assuming that d1 and d2 are Date objects, a valid method called to...
Coding Java Assignment Write the following static methods. Assume they are all in the same class....
Coding Java Assignment Write the following static methods. Assume they are all in the same class. Assume the reference variable input for the Scanner class and any class-level variables mentioned are already declared. All other variables will have to be declared as local unless they are parameter variables. Use printf. A method that prompts for the customer’s name and returns it from the keyboard. A method called shippingInvoice() that prompts for an invoice number and stores it in a class...
Write a Java class called CityDistances in a class file called CityDistances.java.    1. Your methods...
Write a Java class called CityDistances in a class file called CityDistances.java.    1. Your methods will make use of two text files. a. The first text file contains the names of cities. However, the first line of the file is a number specifying how many city names are contained within the file. For example, 5 Dallas Houston Austin Nacogdoches El Paso b. The second text file contains the distances between the cities in the file described above. This file...
(Using Date Class) The following UML Class Diagram describes the java Date class: java.util.Date +Date() +Date(elapseTime:...
(Using Date Class) The following UML Class Diagram describes the java Date class: java.util.Date +Date() +Date(elapseTime: long) +toString(): String +getTime(): long +setTime(elapseTime: long): void Constructs a Date object for the current time. Constructs a Date object for a given time in milliseconds elapsed since January 1, 1970, GMT. Returns a string representing the date and time. Returns the number of milliseconds since January 1, 1970, GMT. Sets a new elapse time in the object. The + sign indicates public modifer...
C++ Start with your Date class in the Date.cpp file (from Date01B assignment or whatever) Name...
C++ Start with your Date class in the Date.cpp file (from Date01B assignment or whatever) Name the new Date file Date03.cpp Add the following constructors to the date class create a constructor that takes 3 integers in the order month, day, year assigns the month, day, year parameters to the corresponding data items. Use the ‘setter’ to assign the values Add a line cout << “in constructor with 3 ints\n” in the constructor a 'default' constructor - no arguments Add...
Write a class called VLPUtility with the following static methods: Java Language 1. concatStrings that will...
Write a class called VLPUtility with the following static methods: Java Language 1. concatStrings that will accept a variable length parameter list of Strings and concatenate them into one string with a space in between and return it. 2. Overload this method with two parameters, one is a boolean named upper and one is a variable length parameter list of Strings. If upper is true, return a combined string with spaces in upper case; otherwise, return the combined string as...
For your homework assignment for week 1 prepare an essay that answers the following questions: 1....
For your homework assignment for week 1 prepare an essay that answers the following questions: 1. A decade ago the idea that medical procedures might move offshore was unthinkable. Today it is a reality. What trends have facilitated this process? Is the globalization of health care good or bad for the American economy? 2. Is the globalization of health care good or bad for patients? Who might benefit from the globalization of health care? Who might lose? 3. How might...
Write a simple java class that contains the following three methods: 1. isosceles -- accepts 3...
Write a simple java class that contains the following three methods: 1. isosceles -- accepts 3 integers which represent the sides of a triangle. Returns true if the triangle is isosceles and false otherwise. 2. perimeter - accepts 3 integers that represent the sides of a triangle and returns the perimeter of the triangle. 3. area -- accepts 3 integers, which represent the sides of a triangle and calculates and returns the area of the triangle. Hint: use Heron's formula....
Implement the following methods. Assume that these will be methods within your myArray class. operator[] Should...
Implement the following methods. Assume that these will be methods within your myArray class. operator[] Should take in an int and return arr at that index if it is a valid index notEqual The notEqual should take in another myArray object and return true if the objects are not equal to one another and false if they are equal. operator-(float) Will subtract the float value that is passed in from each of the values in arr Copy constructor Will take...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT