- @classmethod
Alternative constructor with class method
Class methods are used as Factory methods, they are usually good for alternative constructors. In order to be able to use a method as a class-method
(Calling Date.method(...) one needs to mark the method with the @classmethod decorator)
- Normally we create a Date instance by passing 3 numbers for Year, Monh, Day.
- We would also like to be able to create an instance using a string like this: 2021-04-07
examples/oop/mydate2/mydate.py
class Date: 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) def set_date(self, y, m, d): self.year = y self.month = m self.day = d @classmethod def from_str(cls, date_str): '''Call as d = Date.from_str('2013-12-30') ''' print(cls) year, month, day = map(int, date_str.split('-')) return cls(year, month, day)
examples/oop/mydate2/run.py
from mydate import Date d = Date(2013, 11, 22) print(d) d.set_date(2014, 1, 27) print(d) print('') x = Date.from_str('2013-10-20') print(x) print('') # This works but it is not recommended z = d.from_str('2012-10-20') print(d) print(z)
Date(2013, 11, 22) Date(2014, 1, 27) <class 'mydate.Date'> Date(2013, 10, 20) <class 'mydate.Date'> Date(2014, 1, 27) Date(2012, 10, 20)