Getters and setters in Python

Viewed 525

I'm totally new to Python and I'm trying to write a class, which will store only two attributes, one of which is intended to be a number and another a datetime object. Though I'd also like, while storing date as a datetime, to initialize and output it using a string like "dd.mm.yyyy". So I go:

class MyClass:
    number = None
    date = None

    def __init__(self, params):
        self.number = params["number"]
        self.date = params["date"]

    @property
    def date(self):
        return datetime.datetime.strftime(self.date, '%d.%m.%Y')

    @date.setter
    def date(self, value):
        self.date = datetime.datetime.strptime(value, '%d.%m.%Y')

    def get_vars(self):
        return vars(self)

But at runtime @property points at self.date and says: Expected type 'datetime', got 'str' instead. How can it ever get a string, when it's meant to be converted to date while setting. Why is this happening? Confused.

For example:

>>> MyClass({'number': 42, 'date': '28.12.2017'})
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 8, in __init__
  File "<string>", line 16, in date
  File "<string>", line 16, in date
TypeError: strptime() argument 1 must be str, not datetime.datetime
1 Answers
Related