473,785 Members | 2,421 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Why does __init__ not get called?

I'm still working on my DateTime class from last week...
Why does __init__ not get called?

The docs at
http://www.python.org/dev/doc/devel/...omization.html
read "If __new__() returns an instance of cls, then the new instance's
__init__() method will be invoked" and as far as I can tell cls is very
much an instance of DateTime

************
import datetime
_datetime = datetime.dateti me

class DateTime(_datet ime):
"""
Identical to builtin datetime.dateti me, except it accepts
invalid dates and times as input.
"""
_valid = True
__dict__ = _datetime.__dic t__

def __init__(self, year, month, day, *args, **kw):
print "init called"
_valid = False
self.year = year
self.month = month
self.day = day
self.args = args
self.kw = kw

def throwError():
raise ValueError, 'Invalid Date'
for method in _datetime.__dic t__.keys():
if method!='__doc_ _':
setattr(self, method, throwError)
def __new__(cls, year, month, day, *args, **kw):
print "new called"
try:
return _datetime.__new __(cls, year, month, day, *args,
**kw)
except ValueError:
return cls
*************

Aug 8 '05
11 4299
Steven Bethard wrote:
def __call__(cls, *args, **kwargs):
obj = cls.__new__()
if not isinstance(obj. __class__, cls): ^^^^^^^^^^
issubclass
return obj
obj.__class__._ _init__(obj, *args, **kwargs)
return obj


STeVe
Aug 11 '05 #11
If you subclass strings you have to do your magic in __new__ rather
than __init__. It receives the same arguments as you would normally
expect to go to __init__.

(Except cls rather than self).

Best Regards,

Fuzzy
http://www.voidspace.org.uk/python

Aug 12 '05 #12

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

12
2320
by: Fred Pacquier | last post by:
First off, sorry for this message-in-a-bottle-like post... I haven't been able to phrase my questions well enough to get a meaningful answer from Google in my research. OTOH, it is standard flattery (but true) that this group has a bunch of the nicest and most knowledgeable Usenet people around, and I know for a fact that there are some pretty good spam- related tools written in Python, so I thought I might get away with it :-) Yes,...
6
3717
by: Steven Bethard | last post by:
So when I'm writing a class and I define an __init__ method, I sometimes haven't called object.__init__, e.g.: class C(object): def __init__(self, x): self.x = x instead of class C(object):
9
6218
by: Felix Wiemann | last post by:
Sometimes (but not always) the __new__ method of one of my classes returns an *existing* instance of the class. However, when it does that, the __init__ method of the existing instance is called nonetheless, so that the instance is initialized a second time. For example, please consider the following class (a singleton in this case): >>> class C(object): .... instance = None .... def __new__(cls): .... if C.instance is None:
2
1496
by: Steven Bethard | last post by:
Felix Wiemann wrote: > Steven Bethard wrote: >> http://www.python.org/2.2.3/descrintro.html#__new__ > > > I'm just seeing that the web page says: > > | If you return an existing object, the constructor call will still > | call its __init__ method. If you return an object of a different
0
2727
by: Bill Davy | last post by:
I am working with MSVC6 on Windows XP. I have created an MSVC project called SHIP I have a file SHIP.i with "%module SHIP" as the first line (file is below). I run SHIP.i through SWIG 1.3.24 to obtain SHIP_wrap.cpp and SHIP.py; the latter contains the line "import _SHIP". I compile SHIP_wrap.cpp and a bunch of files into a DLL which I have the
21
12290
by: Sriek | last post by:
hi, i come from a c++ background. i ws happy to find myself on quite familiar grounds with Python. But, what surprised me was the fact that the __init__(), which is said to be the equivlent of the constructor in c++, is not automatically called. I'm sure there must be ample reason for this. I would like to know why this is so? This is my view is more burden on the programmer. Similarly, why do we have to explicitly use the 'self' keyword...
8
1643
by: Ethan Kennerly | last post by:
Hello, There are a lot of Python mailing lists. I hope this is an appropriate one for a question on properties. I am relatively inexperienced user of Python. I came to it to prototype concepts for videogames. Having programmed in C, scripted in Unix shells, and scripted in a number of proprietary game scripting languages, I'm impressed at how well Python meets my needs. In almost all respects, it does what I've been wishing a...
3
2672
by: 7stud | last post by:
When I run the following code and call super() in the Base class's __init__ () method, only one Parent's __init__() method is called. class Parent1(object): def __init__(self): print "Parent1 init called." self.x = 10 class Parent2(object):
4
3547
by: Steven D'Aprano | last post by:
When you call a new-style class, the __new__ method is called with the user-supplied arguments, followed by the __init__ method with the same arguments. I would like to modify the arguments after the __new__ method is called but before the __init__ method, somewhat like this: .... def __new__(cls, *args): .... print "__new__", args
0
9480
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
1
10091
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9950
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8972
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7499
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6739
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
1
4050
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3645
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2879
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.