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
************* 11 4298
Uh... are you actually trying to instantiate this class?
mydate = DateTime(2005, 8, 8)
The reason I ask is that __init__ /is/ called when I run your code on
Python 2.4, provided that the above line is added to the end.
Ah ok, thats interesting I hadn't even tried a valid date yet. Now how
do I get this thing to call __init__ when I pass in an invalid date and
the ValueError is thrown and caught within __new__.
dt = DateTime(2005, 02, 30)
Not takers? This is my attempt to get some attention by bumping my own
post.
I think you have to call type.__new__ like this:
def __new__(cls, year, month, day, *args, **kw):
print "new called"
try:
return _datetime.__new __(cls, year, month, day, *args,
**kw)
except ValueError:
return type.__new__(cl s, ...)
Are you sure you can specify arbitrary arguments to the __new__ method?
I thought they had to be the class object, the tuple of bases, and the
dictionary of names.
> Are you sure you can specify arbitrary arguments to the __new__ method? I thought they had to be the class object, the tuple of bases, and the dictionary of names.
Nevermind, I think I was imagining metaclasses rather than just regular
overriding of __new__
This doesn't work. I'm out of my league here.
What kinds of illegal date values are you trying to represent? The
reason I ask is that it's not going to be as easy as subclassing
datetime... datetime is implemented in C. and so enforcement of legal
values is going to be in the C code. For the time.h functions, you're
also going to be constrained by the size of the time_t struct, which is
probably a long int on your platform. See Modules/datetimemodule. c in
the Python source.
One thing you could do would be to copy datetimemodule. c and build your
own C extension type based on it... things like MAXYEAR 9999 could be
changed that way.
The other thing would be to write a pure-python datetime class without
trying to inherit datetime.dateti me.
I'm out of my league too. I don't know enough about __new__ and
__init__.
I just went another route and did a wrapper for datetime, and didn't
extend it.
Thanks for the effort.
By chance... does anyone know, if I wrote a class, and just wanted to
override __new__ just for the fun of it. What would __new__ look like
so that it behaves exactly the same as it does any other time.
Rob Conner wrote: By chance... does anyone know, if I wrote a class, and just wanted to override __new__ just for the fun of it. What would __new__ look like so that it behaves exactly the same as it does any other time.
Simple:
class C(object):
def __new__(cls, *args, **kwargs):
return super(C, cls).__new__(cl s, *args, **kwargs)
Basically, you're calling object's __new__ method, which in CPython does
something like mallocing the appropriate amount of memory, setting the
__class__ attribute of the object, etc.
Note that __new__() doesn't call __init__(). Both __new__() and
__init__() are called individually by the metaclass. For new-style
classes, "type" is the metaclass, and it's __call__() method looks
something like:
def __call__(cls, *args, **kwargs):
obj = cls.__new__()
if not isinstance(obj. __class__, cls):
return obj
obj.__class__._ _init__(obj, *args, **kwargs)
return obj
(But see Objects/typeobject.c:40 9 for the full gory details.)
STeVe This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
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,...
|
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):
|
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:
|
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
|
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
| |
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...
|
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...
|
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):
|
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
|
by: marktang |
last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look !
Part I. Meaning of...
|
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,...
| |
by: Oralloy |
last post by:
Hello folks,
I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>".
The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed.
This is as boiled down as I can make it.
Here is my compilation command:
g++-12 -std=c++20 -Wnarrowing bit_field.cpp
Here is the code in...
|
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...
|
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...
|
by: TSSRALBI |
last post by:
Hello
I'm a network technician in training and I need your help.
I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs.
The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols.
I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
|
by: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
|
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
| |
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...
| |