V
V
Valery Ryaboshapko2015-09-15 11:29:46
Python
Valery Ryaboshapko, 2015-09-15 11:29:46

How to properly override a class constructor?

Greetings.
Yes, the question seems to be noobish, but somehow I'm completely confused.
There is a class inherited from datetime.date. We need to add a couple of attributes and a couple of properties to this class. To do this, I write the __init__ function in my class, in which I do the usual routine: I check the parameters, create new attributes, and then call the parent class constructor.
When I try to instantiate a class using only the attributes that the parent class accepts, everything is fine. When I try to add more attributes, a TypeError is thrown. CHADNT?
A bit of code. This is what my class looks like.

class MyClass(date):
    def __init__(self, m_year: int, m_month: int, m_day: int,
                 expiry: date=None, *args, **kwargs):
        if expiry:
            self._expiry = expiry
        else:
            self._expiry = date(m_year, m_month, m_day)
        super(Maturity, self).__init__(*args, **kwargs)

    @property
    def expiry(self):
        return {'year': self._expiry.year,
                'month': self._expiry.month,
                'day': self._expiry.day}

We create an instance of the class. So everything is fine, both the methods of the parent class and mine work.
>>> q = MyClass(2015, 5, 5)
>>> q
MyClass(2015, 5, 5)
>>> q.strftime('%Y')
'2015'
>>> q.expiry
{'day': 5, 'month': 5, 'year': 2015}

But as soon as I want more, such an exception falls out.
>>> q = MyClass(2015, 5, 5, expiry=date(2015, 5, 1))
TypeError: function takes at most 3 arguments (4 given)

Among other things, it is confusing that the code works the same way both with the 8th line (super call) and without it.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
angru, 2015-09-15
@valerium

stackoverflow.com/questions/399022/why-cant-i-subc...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question