Python print and types selection

mark.seagoe at gmail.com mark.seagoe at gmail.com
Fri Mar 27 22:43:16 CET 2009


Python 2.5, PC.

I have a question about getting Python print to be able to recognize a
long type.


class bignumber(object):

    def __init__(self, initval=0):
        self.val = initval
#
    def __int__(self):
        print 'bignumber.__int__ returning a %s' % type(self.val)
        return self.val
#
    def __long__(self):
        print 'bignumber.__long__ returning a %s' % type(self.val)
        return long(self.val)

    def str(self):
        return '0x%016X' % self.val
#
print 'TEST 1'
dog = 0x123456789ABCDEF0
print 'type(dog) = %s' % type(dog)
print 'dog val = 0x%016X' % dog

print 'TEST 2'
cat = bignumber(0x55)
print 'cat val = 0x%016X' % cat
print 'type(cat) = %s' % type(cat)

print 'TEST 3'
bird = bignumber(dog)
print 'type(bird) = %s' % type(bird)
print 'bird val = 0x%016X' % long(bird)
print 'bird val = 0x%016X' % bird

When I run this, I get:

TEST 1
type(dog) = <type 'long'>
dog val = 0x123456789ABCDEF0
TEST 2
bignumber.__int__ returning a <type 'int'>
cat val = 0x0000000000000055
type(cat) = <class '__main__.bignumber'>
TEST 3
type(bird) = <class '__main__.bignumber'>
bignumber.__long__ returning a <type 'long'>
bird val = 0x123456789ABCDEF0
bignumber.__int__ returning a <type 'long'>
Traceback (most recent call last):
  File "C:\PythonTesting\bignmber.py, line 32, in <module>
    print 'bird val = 0x%016X' % bird
TypeError: int argument required

Python print recognizes the local constant "dog", but it goes and
fetches the __int__ type from my object-based class, even though it's
value is a long.  Then Python print doesn't expect a long to come back
and bombs out.  I don't want to force the main program to cast the
long value getting returned.  I know Python print can print a long,
but how can I make it select the __long__ instead of the __int__ ?

Thanks.






More information about the Python-list mailing list