473,503 Members | 2,178 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Extending built-in objects/classes

Hi All,

I've reached the point in using Python where projects, instead of being
like 'batch scripts', are becoming more like 'proper' programs.

Therefore, I'm re-designing most of these and have found things in
common which I can use classes for. As I'm only just starting to get
into classes, I see that new style classes are thte way to go, so will
be using those. I come from a C++ background, and understand I need to
adjust my thinking in certain ways - I have read
http://www.geocities.com/foetsch/pyt...le_classes.htm.
As a really simple class, I've decided to make a 'str' to include a
'substr' function. Yes, I know this can be done using slicing, and
effectively this is what substr would do: something like;

class mystr(str):
"""" My rather rubbish but trying to be simple custom string class
"""
def substr(self,start,length,pad=False):
"""
Return str of (up to) _length_ chars, starting at _start_ which
is 1 offset based.
If pad is True, ensure _length_ chars is returned by padding
with trailing whitespace.
""""
return self.<what>[ (start-1): (start-1)+length ]

Ignore the fact pad isn't implemented...

<whatshould be the actual string value of the string object: How do I
work out what this is?
Secondly, I'm not 100% sure what I need for the __init__; is str's
__init__ implicitly called, or do I need to call str's __init__ in
mystr's (I seem to remember seeing some code which did this, as well as
calling super()).

Any critiscm is appreciated.

Many thanks,

Jon.

Jul 3 '06 #1
5 1830
My experiance is mostly with old-style classes, but here goes.

first off, the <whatquestion is actually easier than you think.
After all, self is an instance of a string, so self[3:4] would grab
the slice of characters between 3 and 4 =)

as for __init__, what I have found is that if you do not include an
__init__ function, the parent class's __init__ gets inherited, just
like any other function, so you dont need one. If you have multiple
inheritance, however, you must include an __init__ which calls the
__init__ on every parent, otherwise only the first parent's gets
called.

Jul 3 '06 #2

cm************@yaho.com wrote:
My experiance is mostly with old-style classes, but here goes.

first off, the <whatquestion is actually easier than you think.
After all, self is an instance of a string, so self[3:4] would grab
the slice of characters between 3 and 4 =)
That's kind of funky - I like it. However, I'd still like to know what
<whattechnically is - any ideas on how to find out?
as for __init__, what I have found is that if you do not include an
__init__ function, the parent class's __init__ gets inherited, just
like any other function, so you dont need one. If you have multiple
inheritance, however, you must include an __init__ which calls the
__init__ on every parent, otherwise only the first parent's gets
called.
Thanks for your post: it's most appreciated.

Cheers,

Jon.

Jul 3 '06 #3
On 3/07/2006 7:55 PM, Jon Clements wrote:
cm************@yaho.com wrote:
>My experiance is mostly with old-style classes, but here goes.

first off, the <whatquestion is actually easier than you think.
After all, self is an instance of a string, so self[3:4] would grab
the slice of characters between 3 and 4 =)

That's kind of funky - I like it. However, I'd still like to know what
<whattechnically is - any ideas on how to find out?
You have already been told: you don't need "self.<what>", you just write
"self" ... self *is* a reference to the instance of the mystr class that
is being operated on by the substr method.

You did ask for criticism: here's what's intended to be constructive
criticism: you can often find out answers a lot faster by actually
trying it out yourself. E.g. do I need an __init__() method?

|>class mystr(str):
.... def substr(self, start, length):
.... return self[start-1:start-1+length]
....
|>foo = mystr('abcdef')
|>foo
'abcdef'
|>foo.substr(2, 3)
'bcd'
|>mystr.substr(foo, 2, 3)
'bcd'

No __init__(), no <what>, it just works!

HTH,
John

Jul 3 '06 #4

John Machin wrote:
(snip)
>
You have already been told: you don't need "self.<what>", you just write
"self" ... self *is* a reference to the instance of the mystr class that
is being operated on by the substr method.
(snip)

I get that; let me clarify why I asked again.

As far as I'm aware, the actual representation of a string needn't be
the same as its 'physical' value. ie, a string could always appear in
uppercase ('ABCD'), while stored as 'aBcd'. If I need to guarantee that
substr always returned from the physical representation and not the
external appearance, how would I do this? Or, would self, always return
internal representation, (if so, how would I get external appearance?).

Or I could be talking complete _beep_ - in which case I apologise.

Jon.

Jul 3 '06 #5
On 3/07/2006 10:01 PM, Jon Clements wrote:
John Machin wrote:
(snip)
>You have already been told: you don't need "self.<what>", you just write
"self" ... self *is* a reference to the instance of the mystr class that
is being operated on by the substr method.
(snip)

I get that; let me clarify why I asked again.

As far as I'm aware, the actual representation of a string needn't be
the same as its 'physical' value. ie, a string could always appear in
uppercase ('ABCD'), while stored as 'aBcd'. If I need to guarantee that
substr always returned from the physical representation and not the
external appearance, how would I do this? Or, would self, always return
internal representation, (if so, how would I get external appearance?).

Or I could be talking complete _beep_ - in which case I apologise.

Jon.
The external appearance of an object is produced by repr and str
methods. These transform the internal value into a human-readable (and
Python-compilable, in the case of repr) format. When you are
subclassing, these methods would normally be inherited.

Let's transpose your question into the realm of floats. A float is
usually a 64-bit gizmoid with about 53 bits of mantissa, a sign bit, and
the rest is for the exponent. The external representations are character
strings like '3.3333333333333333e-021'. You want to subclass float so
that you can add handy methods like squared(). You would like it to be
as simple as:

def squared(self):
return self * self

There are two possibilities:
(a) It just works; e.g. print myfloat(1.1).squared() produces 1.21
(b) It doesn't work, you get some mysterious exception like

TypeError: can't multiply sequence by non-int

which you decode as meaning that it doesn't like you trying to multiply
two character strings together, and you have to code the return
expression as self.__internal__ * self.__internal__ or something like that.

1. Which of these possibilities do you think is more
useful/elegant/plausible?
2. [Stop me if you've heard this one before] When you try it out, what
happens?
3. Have you ever seen any indication in the manuals, tutorials, books,
code published online, etc etc as to which possibility has been implemented?

HTH,
John
Jul 3 '06 #6

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

Similar topics

24
3107
by: Jean-Baptiste PERIN | last post by:
Hi, I'm trying to make a windows dll reachable from a python script .. and I'm encountering troubles during link step .. I use "lcc" to compile and link I use python 2.3 under win XP ...
1
3092
by: Alex Elbert | last post by:
Hi I have built dynamic HTMLTable. Now I want to attach it directly to the Email Body - it is already built, so why not to use a ready table. However, I cannot find the way of getting plain HTML...
1
2082
by: William | last post by:
Looking for a pre built dotnet corporate or small business website template.
1
2515
by: John | last post by:
Hello, Is it possible to modify the print dialog box that appears when a user clicks File->Print? Is it possible to make this modification so that all Windows programs use the modified print...
4
1187
by: Brandon Miller | last post by:
All, I have an existing business object (VB.Net) which returns user IDs for our locations in our regions. One of the properties objReg.Manager returns the manager's user id (integer) for a given...
1
1240
by: Johannes Zellner | last post by:
Hello, when extending python there are type methods tp_iter and tp_iternext. Which python code calls the c iterator methods? -- Johannes
10
2218
by: Christophe Peillet | last post by:
I am trying to create a BasePage for use in a large asp.net application, that will centrally provide certain extra properties and logic to the application. (The web project makes use Master Pages...
48
4882
by: meyer | last post by:
Hi everyone, which compiler will Python 2.5 on Windows (Intel) be built with? I notice that Python 2.4 apparently has been built with the VS2003 toolkit compiler, and I read a post from Scott...
1
1930
by: Andreas M. | last post by:
Hi, I could not get info for this on irc.freenode/#xml. I want to extend the ATOM spec with my own namespaced stuff. For this I need to add both some new attributes to the Atom elements as...
0
771
by: bindasho | last post by:
Hello Genious, Please explain the procedure of creating DLL for extending Flash 9. thanks Bhanu
0
7205
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,...
0
7287
Oralloy
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,...
0
7353
jinu1996
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...
0
7468
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...
0
5596
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,...
1
5023
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...
0
4689
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...
0
3180
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...
0
3170
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?

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.