473,246 Members | 1,350 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,246 software developers and data experts.

Questions about subclassing an int

class S(int):
def __init__(self, value):
self.value = value
def addStr(self, str):
self.doc = str

s = S(44)
s.addStr('Hello')

print 's = ', s
print 's.doc = ', s.doc

class T(int):
def __init__(self, value, str):
self.value = value
self.doc = str

t = T(44, 'Goodbye')

print 't = ', t
print 't.doc = ', t.doc

It works ok with S but it fails when I try to instantiate T with a syntax
error. Why?

Also, I don't understand why S works. If I change the name of value and
use something else, the print of s still works by printing the integer
value out. How does it know what value to use? Also, in S.__init__, should
I be calling super(S, self).__init__(value) or is there a difference?

And just for fun:

class R(int):
def __init__(self, value, doc):
super(R, self).__init__(value)
self.doc = doc

r = R(66,'GGG')
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: an integer is required

Now it's no longer a syntax error but I don't see why it's different?

--
Time flies like the wind. Fruit flies like a banana. Stranger things have .0.
happened but none stranger than this. Does your driver's license say Organ ..0
Donor?Black holes are where God divided by zero. Listen to me! We are all- 000
individuals! What if this weren't a hypothetical question?
steveo at syslang.net
Jan 4 '08 #1
2 897
On Jan 4, 10:55*pm, "Steven W. Orr" <ste...@syslang.netwrote:
class S(int):
* * *def __init__(self, value):
* * * * self.value = value
* * *def addStr(self, str):
* * * * self.doc = str

s = S(44)
s.addStr('Hello')

print 's = ', s
print 's.doc = ', s.doc

class T(int):
* * *def __init__(self, value, str):
* * * * self.value = value
* * * * self.doc = str

t = T(44, 'Goodbye')

print 't = ', t
print 't.doc = ', t.doc

It works ok with S but it fails when I try to instantiate T with a syntax
error. Why?

Also, I don't understand why S works. If I change the name of value and
use something else, the print of s still works by printing the integer
value out. How does it know what value to use? Also, in S.__init__, should
I be calling super(S, self).__init__(value) or is there a difference?
I suggest you read http://www.python.org/download/relea....3/descrintro/

Briefly, S(44) calls first S.__new__(S, 44) which does not exist, so
falls back to int.__new__(S, 44) which creates the new object s which
is 44 as an integer. Then *only*, s.__init__(44) is called and your
code is executed. Try changing self.value=value to self.value='SPAM',
you will see that 'print s' still returns 44.

As for T(44, 'Goodbye'), the same happens. First T.__new__ does not
exist, so int.__new__(T, 44, 'Goodbye') is executed and this is where
the error comes from (shouldn't it be a TypeError?) as this means
"create the integer whose representation in base 'Goodbye' is 44".

As for calling int.__init__, there is no point: integers don't have an
__init__() since they are immutable.
And just for fun:

class R(int):
* * *def __init__(self, value, doc):
* * * * *super(R, self).__init__(value)
* * * * *self.doc = doc

r = R(66,'GGG')
Traceback (most recent call last):
* *File "<stdin>", line 1, in ?
TypeError: an integer is required

Now it's no longer a syntax error but I don't see why it's different?
Same as above, though I don't understand why you get a SyntaxError for
T and a TypeError for R. AFAICT both shoult give a TypeError.

--
Arnaud

Jan 4 '08 #2
On Fri, 04 Jan 2008 15:36:27 -0800, Arnaud Delobelle wrote:
Now it's no longer a syntax error but I don't see why it's different?

Same as above, though I don't understand why you get a SyntaxError for T
and a TypeError for R. AFAICT both shoult give a TypeError.
Probably because it was never a SyntaxError in the first place. If you
execute the code given for T, it gives a TypeError, just as you would
expect.

Possibly the Original Poster had mistyped something at some point and got
a SyntaxError, or more likely he's just using "syntax error" to mean
"some exception which I haven't actually looked at".
--
Steven
Jan 5 '08 #3

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

Similar topics

6
by: WhiteRavenEye | last post by:
Why can't I subclass any window except mine in VB? Do I have to write dll for this? I've tried to subclass it with SetWindowLong but without success... Does anyone know how to subclass window...
4
by: GrelEns | last post by:
hello, i wonder if this possible to subclass a list or a tuple and add more attributes ? also does someone have a link to how well define is own iterable object ? what i was expecting was...
2
by: David Vaughan | last post by:
I'm using v2.3, and trying to write to text files, but with a maximum line length. So, if a line is getting too long, a suitable ' ' character is replaced by a new line. I'm subclassing the file...
2
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...
3
by: Peter Olsen | last post by:
I want to define a class "point" as a subclass of complex. When I create an instance sample = point(<arglist>) I want "sample" to "be" a complex number, but with its real and imaginary...
11
by: Brent | last post by:
I'd like to subclass the built-in str type. For example: -- class MyString(str): def __init__(self, txt, data): super(MyString,self).__init__(txt) self.data = data
23
by: Rick | last post by:
Hi, I'm currently preparing for an interview on VB.Net Development.. could someone please give me an idea as to what type of questions can one ask (it's a practical test) and what sort of things...
16
by: manatlan | last post by:
I've got an instance of a class, ex : b=gtk.Button() I'd like to add methods and attributes to my instance "b". I know it's possible by hacking "b" with setattr() methods. But i'd like to do...
17
by: Donn Ingle | last post by:
Hi, Here's a framework for the questions: --- In a module, part of an API --- class Basis ( object ): def foo ( self, arg ): pass --- In user's own code --- class Child ( Basis ):
5
by: Ray | last post by:
Hi all, I am thinking of subclassing the standard string class so I can do something like: mystring str; .... str.toLower (); A quick search on this newsgroup has found messages by others
0
by: abbasky | last post by:
### Vandf component communication method one: data sharing ​ Vandf components can achieve data exchange through data sharing, state sharing, events, and other methods. Vandf's data exchange method...
2
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 7 Feb 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:30 (7.30PM). In this month's session, the creator of the excellent VBE...
0
Git
by: egorbl4 | last post by:
Скачал я git, хотел начать настройку, а там вылезло вот это Что это? Что мне с этим делать? ...
0
by: DolphinDB | last post by:
The formulas of 101 quantitative trading alphas used by WorldQuant were presented in the paper 101 Formulaic Alphas. However, some formulas are complex, leading to challenges in calculation. Take...
0
by: Aftab Ahmad | last post by:
Hello Experts! I have written a code in MS Access for a cmd called "WhatsApp Message" to open WhatsApp using that very code but the problem is that it gives a popup message everytime I clicked on...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: marcoviolo | last post by:
Dear all, I would like to implement on my worksheet an vlookup dynamic , that consider a change of pivot excel via win32com, from an external excel (without open it) and save the new file into a...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...

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.