473,657 Members | 2,505 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,sta rt,length,pad=F alse):
"""
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 1840
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
<whattechnicall y 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
<whattechnicall y 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.333333333333 3333e-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).sq uared() 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
3136
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 Here's the compile command which seems to work well : -----------------------------------------------------
1
3108
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 text out of dynamically built control. I tried to put my table between div and read div.innerHTML then - HTTP exception has been thrown. Any thoughts, ladies and gentelmen
1
2095
by: William | last post by:
Looking for a pre built dotnet corporate or small business website template.
1
2528
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 dialog box? What about just changing the print dialog box used by Internet Explorer?
4
1197
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 location. What I'd like to do is implement something similar to .ToString, so I might call - objReg.Manager.GetUser() This would return a User object (which we already have written) representing
1
1246
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
2235
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 as well.) I want to make a property named TitleResourceKey, for example, that contains the resource key used to translate the page title and, using reflection and the CustomLocalisationKey attribute that points to the property this key...
48
4919
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 David Daniels where he said that probably the VS2003 toolkit will be used for Python 2.5 again. However, even before the release of Python 2.5, I cannot seem to find many retailers around here that still carry Visual Studio 2003, and some were a...
1
1939
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 well as adding my own elements, both under the root as well as contained in my own containers. I do not find any valuable info on this. Any link aprreciated,
0
781
by: bindasho | last post by:
Hello Genious, Please explain the procedure of creating DLL for extending Flash 9. thanks Bhanu
0
8420
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
8324
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,...
0
8842
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, 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...
0
8617
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
7353
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
6176
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
5642
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();...
0
4173
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...
2
1970
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.