Subclass of int and initialisation with not integer values

Jeff Epler jepler at unpythonic.net
Wed Apr 24 12:14:54 EDT 2002


On Wed, Apr 24, 2002 at 05:09:53PM +0200, Boris Boutillier wrote:
> Hi all,
> 
> I've got a little problem with subclass of int.

You must create a __new__ method.  See the descrinfo.html talk about
how it works.


class toto(int):
    true, false = 'O', 'N'
    def __init__(self, str):
	self.str = str

    def __new__(cls, val):
	if val == cls.true: 
	    return int.__new__(cls, 1)
	elif val == cls.false:
	    return int.__new__(cls, 0)
	else:
	    raise ValueError

    def __str__(self):
	return self.str

print toto('N')
print toto('O')
print toto(0)

Jeff





More information about the Python-list mailing list