Why can't I subclass off of "date" ?

D

davidfinance

Ok, maybe this is a stupid question, but why can't I make a subclass of
datetime.date and override the __init__ method?

---

from datetime import date

class A(date):
def __init__(self, a, b, c, d):
print a, b, c, d
date.__init__(self, 2006, 12, 11)

d = A(1, 2, 3, 4)

---

$ python break_date.py
Traceback (most recent call last):
File "break_date.py", line 9, in ?
d = A(1, 2, 3, 4)
TypeError: function takes exactly 3 arguments (4 given)


If I make A a subclass of some toy class that is constructed with three
arguments, it works fine. Why can't I make "date" the subclass?

Thanks for any advice.

David
 
G

Georg Brandl

Ok, maybe this is a stupid question, but why can't I make a subclass of
datetime.date and override the __init__ method?

---

from datetime import date

class A(date):
def __init__(self, a, b, c, d):
print a, b, c, d
date.__init__(self, 2006, 12, 11)

d = A(1, 2, 3, 4)

---

$ python break_date.py
Traceback (most recent call last):
File "break_date.py", line 9, in ?
d = A(1, 2, 3, 4)
TypeError: function takes exactly 3 arguments (4 given)


If I make A a subclass of some toy class that is constructed with three
arguments, it works fine. Why can't I make "date" the subclass?

You'll have to also override the __new__ method.

Georg
 
F

Fredrik Lundh

Ok, maybe this is a stupid question, but why can't I make a subclass of
datetime.date and override the __init__ method?

__init__ controls initialization of an already constructed object. to
control construction, you need to override __new__:

http://pyref.infogami.com/__new__

e.g.

class A(date):
def __new__(cls, a, b, c, d):
print a, b, c, d
return super(A, cls).__new__(cls, 2006, 12, 11)

</F>
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,786
Messages
2,569,626
Members
45,328
Latest member
66Teonna9

Latest Threads

Top