473,788 Members | 2,810 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Returning same type as self for arithmetic in subclasses

# -*- coding: latin-1 -*-
"""
I subclass datetime and timedelta
dt = myDatetime(1970 ,1,1)
type(dt) <class 'dtime.myDateti me'>
td = myTimedelta(hou rs=1)
type(td) <class 'dtime.myTimede lta'>

But when I do arithmetic with these classes, they return datetime and
timedelta,
where I want them to return myDatetime and myTimedelta
new_time = dt + td
new_time datetime.dateti me(1970, 1, 1, 1, 0)
type(new_time)

<type 'datetime.datet ime'>

So I wondered if there was a simlpler way to coerce the result into my
desired
types rather than overwriting the __add__, __sub__ etc. methods?

"""

from datetime import datetime, timedelta

class myDatetime(date time):
pass

class myTimedelta(tim edelta):
pass
if __name__ == "__main__":

import os.path, doctest, dtime
# import and test this file
doctest.testmod (dtime)


--

hilsen/regards Max M, Denmark

http://www.mxm.dk/
IT's Mad Science
Jul 18 '05 #1
3 1897
[Max M]
"""
I subclass datetime and timedelta
dt = myDatetime(1970 ,1,1)
type(dt) <class 'dtime.myDateti me'>
td = myTimedelta(hou rs=1)
type(td) <class 'dtime.myTimede lta'>

But when I do arithmetic with these classes, they return datetime and
timedelta, ....
new_time = dt + td
new_time datetime.dateti me(1970, 1, 1, 1, 0)
type(new_time)

<type 'datetime.datet ime'>


Yes, and all builtin Python types work that way. For example,
int.__add__ or float.__add__ applied to a subclass of int or float
will return an int or float; similarly for a subclass of str. This
was Guido's decision, based on that an implementation of any method in
a base class has no idea what requirements may exist for invoking a
subclass's constructor. For example, a subclass may restrict the
values of constructor arguments, or require more arguments than a base
class constructor; it may permute the order of positional arguments in
the base class constructor; it may even be "a feature" that a subclass
constructor gives a different meaning to an argument it shares with
the base class constructor. Since there isn't a way to guess, Python
does a safe thing instead.
where I want them to return myDatetime and myTimedelta

So I wondered if there was a simlpler way to coerce the result into my
desired types rather than overwriting the __add__, __sub__ etc. methods?


Generally speaking, no. But I'm sure someone will torture you with a
framework that purports to make it easy <wink>.
Jul 18 '05 #2
Tim Peters wrote:
Yes, and all builtin Python types work that way. For example,
int.__add__ or float.__add__ applied to a subclass of int or float
will return an int or float; similarly for a subclass of str. This
was Guido's decision...
I will not discuss it with him. He is usually right :-s

Generally speaking, no. But I'm sure someone will torture you with a
framework that purports to make it easy <wink>.


Apparently not... But here is my solution.

If anybody is interrested. It should also be obvious what I am working on.

Btw. I really love doctests ... Unittests are a nice idea. But doctest
is a really practical solution.

############### ############### #

class vDatetime(datet ime):
"""
A subclass of datetime, that renders itself in the iCalendar datetime
format.
dt = vDatetime(1970, 1,1, 12, 30, 0)
str(dt) '19700101T12300 0'
dt2 = vDatetime(1970, 1,1, 0, 0, 0)
str(dt - dt2) 'PT12H30M'

Adding is not allowed dt + dt2

Traceback (most recent call last):
...
AttributeError: 'NotImplemented Type' object has no attribute 'days'
"""

def __init__(self, *args, **kwargs):
datetime.__init __(self, *args, **kwargs)
self.params = Params()

def __add__(self, other):
return self._to_vdatet ime(datetime.__ add__(self, other))

def __sub__(self, other):
return self._to_vdatet ime(datetime.__ sub__(self, other))

def _to_vdatetime(s elf, result):
if hasattr(result, 'timetuple'):
return vDatetime(*resu lt.timetuple()[:6])
return vDuration(resul t.days, result.seconds)

def fromstring(st):
"Class method that parses"
try:
timetuple = map(int, ((
st[:4], # year
st[4:6], # month
st[6:8], # day
st[9:11], # hour
st[11:13], # minute
st[13:15], # second
)))
except:
raise ValueError, 'Wrong format'
return vDatetime(*time tuple)
fromstring = staticmethod(fr omstring)

def __str__(self):
return self.strftime(" %Y%m%dT%H%M%S")

--

hilsen/regards Max M, Denmark

http://www.mxm.dk/
IT's Mad Science
Jul 18 '05 #3
Tim Peters wrote:
[Max M]
"""
I subclass datetime and timedelta
[...]
Generally speaking, no. But I'm sure someone will torture you with a
framework that purports to make it easy <wink>.


Clearly the easy way is to have the type declaration introspect on the
definitions of datetime and timedelta and then auto-create methods
wrapping the base types' methods in a "myxxx" conversion.

left-as-an-exercise-for-the-reader-ly y'rs - steve
--
Steve Holden http://www.holdenweb.com/
Python Web Programming http://pydish.holdenweb.com/
Holden Web LLC +1 703 861 4237 +1 800 494 3119
Jul 18 '05 #4

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

Similar topics

21
4538
by: Batista, Facundo | last post by:
Here I send it. Suggestions and all kinds of recomendations are more than welcomed. If it all goes ok, it'll be a PEP when I finish writing/modifying the code. Thank you. .. Facundo
17
23173
by: Sean Ross | last post by:
Hi. Recently I made a small script to do some file transferring (among other things). I wanted to monitor the progress of the file transfer, so I needed to know the size of the files I was transferring. Finding out how to get this information took some time (reading the manuals - googling did not prove worthwhile). Anyway, I did eventually figure out how to do it (there are a few ways, including os.path.getsize(filename)). My...
8
4163
by: Robin Becker | last post by:
Hi, just trying to avoid wheel reinvention. I have need of an unsigned 32 bit arithmetic type to carry out a checksum operation and wondered if anyone had already defined such a beast. Our current code works with 32 bit cpu's, but is failing with 64 bit comparisons; it's clearly wrong as we are comparing a number with a negated number; the bits might drop off in 32 bits, but not in 64. -- Robin Becker
11
1618
by: Paulo da Silva | last post by:
I would like to implement something like this: class C1: def __init__(self,xxx): if ... : self.foo = foo self.bar = bar else: self=C1.load(xxx)
3
4512
by: dgdev | last post by:
I would like to pickle an extension type (written in pyrex). I have it working thus far by defining three methods: class C: # for pickling __getstate__(self): ... # make 'state_obj' return state_obj __reduce__(self):
1
1671
by: Niels Ull | last post by:
Hi! I have a generic abstract base class MyCollection<Twhich represents a collection of T's with some common utility methods. I then have a number of non-generic subclasses, e.g. class FooCollection : MyCollection<Foo> { /* utility methods only for foo collections */ }
12
2173
by: Frank Millman | last post by:
Hi all I have a standard requirement for a 'decimal' type, to instantiate and manipulate numeric data that is stored in a database. I came up with a solution long before the introduction of the Decimal type, which has been working well for me. I know the 'scale' (number of decimal places) of the number in advance. When I read the number in from the database I scale it up to an integer. When I write it back I scale it down again. All...
21
5202
by: Nikolaus Rath | last post by:
Hello, Can someone explain to me the difference between a type and a class? After reading http://www.cafepy.com/article/python_types_and_objects/ it seems to me that classes and types are actually the same thing: - both are instances of a metaclass, and the same metaclass ('type') can instantiate both classes and types. - both can be instantiated and yield an "ordinary" object - I can even inherit from a type and get a class
18
2462
by: Stephan Beal | last post by:
Hi, all! Before i ask my question, i want to clarify that my question is not about the code i will show, but about what the C Standard says should happen. A week or so ago it occurred to me that one can implement a very basic form of subclassing in C (the gurus certainly already know this, but it was news to me). What i've done (shown below) seems to work all fine and well, and does exactly what i'd expect, but i'm asking about
0
9656
marktang
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...
0
9498
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
10110
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
9967
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...
1
7517
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
5398
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...
0
5536
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4069
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
3
2894
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.