Questions about subclassing an int

Steven W. Orr steveo at syslang.net
Fri Jan 4 17:55:33 EST 2008


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



More information about the Python-list mailing list