Why doesn't this work?

R

Ron Garret

Python 2.3.5 (#1, Jan 30 2006, 13:30:29)
[GCC 3.3 20030304 (Apple Computer, Inc. build 1819)] on darwin
Type "help", "copyright", "credits" or "license" for more information..... def __init__(self): pass
.... Traceback (most recent call last):
 
L

Larry Bates

Because datetime is a new-style class:

The Constructor __new__

If you are like me, then you probably always thought of the __init__ method as
the Python equivalent of what is called a constructor in C++. This isn't the
whole story.

When an instance of a class is created, Python first calls the __new__ method of
the class. __new__ is a static method that is called with the class as its first
argument. __new__ returns a new instance of the class.

The __init__ method is called afterwards to initialize the instance. In some
situations (think "unplickling"!), no initialization is performed. Also,
immutable types like int and str are completely constructed by the __new__
method; their __init__ method does nothing. This way, it is impossible to
circumvent immutability by explicitly calling the __init__ method after
construction.


I think what you wanted was:
.... def __new__(self): pass
....
-Larry
 
R

Ron Garret

Larry Bates said:
Because datetime is a new-style class:
Ah.

The Constructor __new__

If you are like me, then you probably always thought of the __init__ method
as
the Python equivalent of what is called a constructor in C++. This isn't the
whole story.

When an instance of a class is created, Python first calls the __new__ method
of
the class. __new__ is a static method that is called with the class as its
first
argument. __new__ returns a new instance of the class.

The __init__ method is called afterwards to initialize the instance. In some
situations (think "unplickling"!), no initialization is performed. Also,
immutable types like int and str are completely constructed by the __new__
method; their __init__ method does nothing. This way, it is impossible to
circumvent immutability by explicitly calling the __init__ method after
construction.


I think what you wanted was:

... def __new__(self): pass
...

-Larry

Thanks!

rg
 

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

Forum statistics

Threads
473,770
Messages
2,569,584
Members
45,075
Latest member
MakersCBDBloodSupport

Latest Threads

Top