0

brand new here!

This is my first time working with Python classes and I am a bit confused. I wanted to try and store dates with three attributes - year, month, and day (as integers).

What I want to do is:

for an ____init____() function to take a year, month and a date (with defaults 1900, 1 and 1) and return it with the month written out:

>>date_one = Date( 1973, 5, 2)
May 2, 1973
>>date_two = Date( 1984)
January 1, 1984

for a ____str____() function to format the data as a string with year, month, and day:

>>date_one = Date( 1973, 5, 2)
>>string = str(date_one)
>>string
'1973-05-02'
>>date_two = Date( 1984)
>>print date_two
1984-01-01

for same_date_in_year() to determine whether two dates fall on the same date, even if they aren't in the same year

>>date_one = Date( 1972, 3, 27)
>>date_two = Date( 1998, 4, 17)
>>date_three = Date(1957, 4, 17)
>>date_one.same_date_in_year(date_two)
False
>>date_two.same_date_in_year(date_three)
True

What I have so far:

days_in_month = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]

month_names = ['', 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']

class Date(object):
    year = 1900
    month = 1
    day = 1

    def __init__(self, year=1900, month=1, day=1):
        self.year, self.month, self.day = year, month, day
        print month_names[month], str(day)+', '+str(year)

    def __str__(self, year=1900, month=1, day=1):
        self.year, self.month, self.day = year, month, day
        print str(year)+'-'+str(month).rjust(2,'0')+'-'+str(day).rjust(2,'0')


    def same_date_in_year(year, month, day):

    pass


if __name__ == "__main__":
    date_one = Date( 1972, 3, 27 )
    date_two = Date( 1998, 4, 13 )
    date_three = Date( 1996, 4, 13 )
    print "date_one is " + str(date_one)
    print "date_two is " + str(date_two)
    print "date_three is " + str(date_three)
    print "date_one.same_day_in_year(date_two)", date_one.same_day_in_year(date_two)
    print "date_two.same_day_in_year(date_three)", date_two.same_day_in_year(date_three)
    print  

I have no idea how the Class would work and the functions inside it, before the pass. If someone could help me, it would be much appreciated!

Mariankka
  • 89
  • 3
  • 10
  • 2
    This is far too broad for Stack Overflow. I think most people would be happy to help you with *specific* questions, but nobody wants to do all your homework for you. So break your big problem down into smaller ones and ask those instead. – Shashank Apr 29 '15 at 04:00
  • I would be happy with just the __init__ function. I just want to understand how classes work. – Mariankka Apr 29 '15 at 04:01
  • A class's initializer shouldn't "return" or "print out" a value; it just should return an instance of that class. You can then add a `__repr__` method to that class so that, when someone tries to look at an instance of it, they see what you want instead of `<__main__.Date at 0x12345678>`. – abarnert Apr 29 '15 at 04:04
  • Anyway, the Tutorial chapter on [Classes](https://docs.python.org/2/tutorial/classes.html) explains this far better than a random StackOverflow user is liable to, with multiple examples. For example, the [Class Objects](https://docs.python.org/2/tutorial/classes.html#class-objects) section shows a perfectly simple but real-life example of an `__init__` method for a `Complex` class. – abarnert Apr 29 '15 at 04:06
  • Meanwhile, I think this deserves to be closed, and therefore not answered, because it's not appropriate for StackOverflow. But it's not a bad question in general, just wrong for SO, and an example of what you want is so trivial to write, so I wrote it [here](http://pastebin.com/yKWwBgwF). Some of the details are probably not right, but you should be able to use that as a starting point. – abarnert Apr 29 '15 at 04:13
  • Thank you! So, __init__ is working but do you have any idea why __str__ isn't printing after every run-through of __name__ (I edited it). – Mariankka Apr 29 '15 at 05:16

2 Answers2

0

As you say in your comment, you're looking for some help with the init method, and may be able to finish the rest off on your own.

class MDate(Object):
  """Example Date class for learning purposes. Note the prefix 'M' in the
     class name to avoid conflicts with built-in classes."""
  def __init__(self, year=1900, month=1, day=1):
    for arg in [year, month, day]:
      if type(arg) != int:
        raise TypeException('Year, month, and day must be `int`')

    self.year = year
    self.month = month
    self.day = day
Patrick McLaren
  • 978
  • 10
  • 22
-1

I am somewhat new to Python as well. May I suggest the following solution where you simply extend a date class that is already available in Python? Python has "batteries included" which means you do not have to repeat yourself by taking advantage of the Standard Library.

When first learning Python, I found myself constantly reinventing the wheel, or date object in this case, until I understood the concept of extending a Python class.

# import date type from modules included with Python install
from datetime import date


class Date(date):  # extend the date type imported above
    # some date formats, see http://strftime.org/ for values
    year_month_day = "%Y %m %d"
    month_day_year = "%m %d %Y"

    # *args and **kwargs are the arguments and key word arguments
    # passed when date object is created
    def __init__(self, *args, **kwargs):
        # set a default string_format from choices defined above
        # that is used in the __str__ and __repr__ functions
        self.string_format = self.year_month_day
        # call the __init__ on parent `date` object
        # passing all args and kwargs passed on object creation
        # at date = Date(1970, 1, 1)
        super(Date, self).__init__(*args, **kwargs)

    def __repr__(self):
        # date has a function called `strftime` that takes
        # a string format and returns the formatted date
        return self.strftime(self.string_format)

    def __str__(self):
        return self.strftime(self.string_format)

Example usage of extended class:

In: date_one = Date(1970, 1, 1)

In: print date_one

# as defined by date.string_format value "%Y %m %d"

Out: 1970 01 01

# change the string_format value to "%m %d %Y"

In: date_one.string_format = date_one.month_day_year

In: print date_one

Out: 01 01 1970

You can also set a string format like so:

In: date_one.string_format = "%c"

In: print date_one

Out: Thu Jan 1 00:00:00 1970

This link on special methods overriding in Python may be helpful.

Community
  • 1
  • 1
dmmfll
  • 2,666
  • 2
  • 35
  • 41