2

Happy new years guys!

I'm new to Python and have been experimenting with class inheritance. I created the code below and have a few questions -

  1. Why is shDate3 of type numpy.datetime64 instead of SHDate3? shDate seems to be of type SHDate, which is the behavior I was expecting.
  2. Why can't shDate2 be created? I'm receiving "'an integer is required'" error...

Thanks a lot!

from datetime import *
from numpy import *

class SHDate(date):
    def __init__(self, year, month, day):
        date.__init__(self, year, month, day)

class SHDate2(date):
    def __init__(self, dateString):
        timeStruct = strptime(dateString, "%Y-%m-%d")
        date.__init__(self, timeStruct.tm_year, timeStruct.tm_mon, timeStruct.tm_mday)

class SHDate3(datetime64):
    def __init__(self, dateString):
        super(SHDate3, self).__init__(dateString)

if __name__ == '__main__':
    shDate = SHDate(2010,1,31)
    print type(shDate)

    shDate3 = SHDate3("2011-10-11")
    print shDate3
    print type(shDate3)

    shDate2 = SHDate2("2011-10-11")
    print shDate2

1 Answer 1

2

Quick answers:

  1. Make sure you know when you should use either type or isinstance, they are different. You may want to take a look at this question, it clarifies type and isinstance usage.
  2. You shouldn't be using __init__ to custom your date class, because it is an immutable class. This question provides some discussion on customizing instances for those classes.
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.