@methodclass in python 1

@methodclass in python

class Date(object):

    def __init__(self, day=0, month=0, year=0):
        self.day = day
        self.month = month
        self.year = year

    @classmethod
    def from_string(cls, date_as_string):
        day, month, year = map(int, date_as_string.split('-'))
        date1 = cls(day, month, year)
        return date1

    @staticmethod
    def is_date_valid(date_as_string):
        day, month, year = map(int, date_as_string.split('-'))
        return day <= 31 and month <= 12 and year <= 3999

date2 = Date.from_string('11-09-2012')
is_date = Date.is_date_valid('11-09-2012')

Here is what the above code is Doing:
1. We create a class Date.
2. We create a class method from_string that takes a date in string format and creates an instance of Date.
3. We create a static method is_date_valid that takes a date in string format and returns True if it is a valid date and False otherwise.
4. We create an instance of Date by calling the class method from_string.
5. We call the static method is_date_valid to check if the date is valid.

Similar Posts