With assistance from Gabriel and Frederik (and a few old threads in
c.l.p.) I've been making headway on my specialized datetime class. Now
I'm puzzled by behavior I didn't expect while attempting to use some of
the alternate datetime constructors. Specifically, it appears if I
call GeneralizedTime .now() it calls the __new__ method of my class but
treats keyword arguments as if they were positional.
My class:
class GeneralizedTime (datetime):
def __new__(cls, time=None, *args, **kwargs):
print time, args, kwargs
if isinstance(time , str):
timeValues, tzOffset = cls.stringToTim eTuple(time)
return datetime.__new_ _(cls, tzinfo=GenericT Z(tzOffset),
**timeValues)
elif isinstance(time , datetime):
timeValues = time.timetuple( )[:6]
tzOffset = time.utcoffset( )
return datetime.__new_ _(cls, tzinfo=GenericT Z(tzOffset),
*timeValues)
elif time is None:
print "Still gotta figure out now to do this one..."
else:
raise Invalidtime(tim e)
@staticmethod
def stringToTimeTup le(timeString):
... regex that parses timeString ...
>>GeneralizedTi me.today()
2006 (11, 16, 0, 35, 18, 747275, None) {}
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "gentime.py ", line 106, in __new__
raise InvalidTime(tim e)
gentime.Invalid Time: 2006
So it appears the time tuple is being passed to
GeneralizedTime .__new__, but the first value is being assigned to the
"time" argument.
Is this a side effect of how datetime is implemented? Or am I doing
something screwy?
Thanks!
-Ben 3 1376 in****@gmail.co m wrote:
With assistance from Gabriel and Frederik (and a few old threads in
c.l.p.) I've been making headway on my specialized datetime class. Now
I'm puzzled by behavior I didn't expect while attempting to use some of
the alternate datetime constructors. Specifically, it appears if I
call GeneralizedTime .now() it calls the __new__ method of my class but
treats keyword arguments as if they were positional.
My class:
class GeneralizedTime (datetime):
def __new__(cls, time=None, *args, **kwargs):
datetime.dateti me() takes these arguments: year, month, day[, hour[,
minute[, second[, microsecond[, tzinfo]]]]]), see http://docs.python.org/lib/datetime-datetime.html
print time, args, kwargs
if isinstance(time , str):
timeValues, tzOffset = cls.stringToTim eTuple(time)
return datetime.__new_ _(cls, tzinfo=GenericT Z(tzOffset),
**timeValues)
elif isinstance(time , datetime):
timeValues = time.timetuple( )[:6]
time.timetuple( ) does not exist, see http://docs.python.org/lib/module-time.html, time is represented as a
tuple. checkout time.mktime() on how to convert to a tuple to a time
tzOffset = time.utcoffset( )
return datetime.__new_ _(cls, tzinfo=GenericT Z(tzOffset),
*timeValues)
elif time is None:
print "Still gotta figure out now to do this one..."
else:
raise Invalidtime(tim e)
@staticmethod
def stringToTimeTup le(timeString):
... regex that parses timeString ...
>GeneralizedTim e.today()
2006 (11, 16, 0, 35, 18, 747275, None) {}
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "gentime.py ", line 106, in __new__
raise InvalidTime(tim e)
gentime.Invalid Time: 2006
So it appears the time tuple is being passed to
GeneralizedTime .__new__, but the first value is being assigned to the
"time" argument.
Is this a side effect of how datetime is implemented? Or am I doing
something screwy?
Thanks!
-Ben
A very cutback part of your code gets the basics working:
from datetime import datetime
class Invalidtime(Exc eption):
pass
class GeneralizedTime (datetime):
def __new__(cls, *args, **kwargs):
if isinstance(args , tuple):
return datetime.__new_ _(cls, *args)
else:
raise Invalidtime(arg s)
t = GeneralizedTime .today()
print t.year
print t.month
print t.day
print t.hour
print t.minute
print t.second
print t.microsecond
print t.tzinfo in****@gmail.co m wrote:
With assistance from Gabriel and Frederik (and a few old threads in
c.l.p.) I've been making headway on my specialized datetime class. Now
I'm puzzled by behavior I didn't expect while attempting to use some of
the alternate datetime constructors. Specifically, it appears if I
call GeneralizedTime .now() it calls the __new__ method of my class but
treats keyword arguments as if they were positional.
My class:
class GeneralizedTime (datetime):
def __new__(cls, time=None, *args, **kwargs):
print time, args, kwargs
if isinstance(time , str):
timeValues, tzOffset = cls.stringToTim eTuple(time)
return datetime.__new_ _(cls, tzinfo=GenericT Z(tzOffset),
**timeValues)
elif isinstance(time , datetime):
timeValues = time.timetuple( )[:6]
tzOffset = time.utcoffset( )
return datetime.__new_ _(cls, tzinfo=GenericT Z(tzOffset),
*timeValues)
elif time is None:
print "Still gotta figure out now to do this one..."
else:
raise Invalidtime(tim e)
@staticmethod
def stringToTimeTup le(timeString):
... regex that parses timeString ...
>>>GeneralizedT ime.today()
2006 (11, 16, 0, 35, 18, 747275, None) {}
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "gentime.py ", line 106, in __new__
raise InvalidTime(tim e)
gentime.Invalid Time: 2006
So it appears the time tuple is being passed to
GeneralizedTime .__new__, but the first value is being assigned to the
"time" argument.
Is this a side effect of how datetime is implemented?
Yes. Consider:
>>def today(time=None , *args):
.... print "time = ", time, "args = ", args
....
>>today(2006, 11, 16)
time = 2006 args = (11, 16)
To fix the issue you'll probably have to remove the time=None parameter from
GeneralizedTime .__new__() and instead extract it from args or kwargs.
Peter
Yes. Consider:
>
>def today(time=None , *args):
... print "time = ", time, "args = ", args
...
>today(2006, 11, 16)
time = 2006 args = (11, 16)
To fix the issue you'll probably have to remove the time=None parameter from
GeneralizedTime .__new__() and instead extract it from args or kwargs.
D'oh. That *should* have been obvious.
I am now no longer allowed to program after midnight.
Thanks!
-Ben This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
by: BJörn Lindqvist |
last post by:
A problem I have occured recently is that I want to subclass builtin
types. Especially subclassing list is very troublesome to me. But I
can't find the right syntax to use. Take for example this class which
is supposed to be a representation of a genome:
class Genome(list):
def __init__(self):
list.__init__(self)
self =
....
|
by: Christopher P. Winter |
last post by:
I'm seeing some unexpected behavior with Text-indent, as shown on this
page:
http://www.chris-winter.com/Digressions/HP_Kayak/My_Kayak.html
I set up the following style rules for footnotes:
DIV.FootRule { Border-bottom: 1px Solid Gray; Margin-bottom:
2px; Text-align: Left; Width: 20% }
|
by: Sahil Malik [MVP] |
last post by:
Okay so lets say I have a valuetype - lets say DateTime.
Look at this code .
List<DateTime> dt = new List<DateTime>() ;
dt.Add(new dateTime(1999,12,1))
dt.AddDays(1) ;
<--- This statement won't actually change the date time stored in the
List<T> dt.
|
by: ToddLMorgan |
last post by:
I'm just starting out with python, after having a long history with
Java. I was wondering if there were any resources or tips from anyone
out there in Python-land that can help me make the transition as
successfully as possible? Perhaps you've made the transition yourself
or just have experience with folks who have made the transition.
I'm looking for the common types of mistakes that say a Java/C# or
even C++ developer may commonly...
|
by: Paulo da Silva |
last post by:
Hi!
What's wrong with this way of subclassing?
from datetime import date
class MyDate(date):
def __init__(self,year,month=None,day=None):
if type(year) is str:
# The whole date is here as a string
| |
by: Mike Rooney |
last post by:
Hi everyone, this is my first post to this list. I am trying to create a
subclass of datetime.date and pickle it, but I get errors on loading it
back. I have created a VERY simple demo of this:
import datetime
class MyDate(datetime.date):
"""
This should be pickleable.
|
by: Rajeet Dalawal |
last post by:
Good day group.
I was asked in an interview to explain the behavior of this program.
void main()
{
char *s = "abc";
int *i = (int *) s;
printf("%x", *i);
}
|
by: Christian Heimes |
last post by:
Rick King schrieb:
datetime.date is a C extension class. Subclassing of extension classes
may not always work as you'd expect it.
Christian
|
by: =?Utf-8?B?QmV0aA==?= |
last post by:
Hello.
I'm trying to figure out how to create subclasses with properties specific
to the subclass and so far it isn't going well.
Right now I have a class with an enum representing the type. The class has
all the properties specific to all the types, but what I want instead is to
move those properties to subclasses specific to each type.
I have code like this:
|
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: jinu1996 |
last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth.
The Art of Business Website Design
Your website is...
|
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,...
|
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...
|
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();...
|
by: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
|
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
| |
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...
| |