Class and static methods



examples/oop/class_and_static_method/mydate.py
def other_method(val):
    print(f"other_method: {val}")

class Date(object):
    def __init__(self, Year, Month, Day):
        self.year  = Year
        self.month = Month
        self.day   = Day

    def __str__(self):
        return 'Date({}, {}, {})'.format(self.year, self.month, self.day)

    @classmethod
    def from_str(class_object, date_str):
        '''Call as
           d = Date.from_str('2013-12-30')
        '''
        print(f"from_str: {class_object}")
        year, month, day = map(int, date_str.split('-'))

        other_method(43)

        if class_object.is_valid_date(year, month, day):
            return class_object(year, month, day)
        else:
            raise Exception("Invalid date")

    @staticmethod
    def is_valid_date(year, month, day):
        if 0 <= year <= 3000 and  1 <= month <= 12 and 1 <= day <= 31:
            return True
        else:
            return False

examples/oop/class_and_static_method/run.py
import mydate

dd = mydate.Date.from_str('2013-10-20')
print(dd)

print('')
print(mydate.Date.is_valid_date(2013, 10, 20))
print(mydate.Date.is_valid_date(2013, 10, 32))
print('')

x = mydate.Date.from_str('2013-10-32')

from_str: <class 'mydate.Date'>
other_method: 43
Date(2013, 10, 20)

True
False

from_str: <class 'mydate.Date'>
other_method: 43
Traceback (most recent call last):
  File "run.py", line 11, in <module>
    x = mydate.Date.from_str('2013-10-32')
  File "/home/gabor/work/slides/python-programming/examples/classes/mydate4/mydate.py", line 26, in from_str
    raise Exception("Invalid date")
Exception: Invalid date