[Python-Dev] Puzzling behavior when subclassing from float
Charles G Waldman
cgw@alum.mit.edu
Fri, 20 Sep 2002 09:37:15 -0700
Aplogies in advance if this is the wrong forum for this question.
I'm trying to understand some puzzling behavior related to subclassing
from built-in types.
I'm running Python 2.2.1
If I subclass from "dict", it seems that the base class constructor is
not being called, which is just as I would expect:
class D(dict):
def __init__(self, spam, eggs):
print "spam=",spam, "eggs=", eggs
>>> d = D(1,2)
spam= 1 eggs= 2
>>> print d
{}
But if I subclass from "float", some magic is happening, which I don't
quite understand - it seems that the base class constructor *is* called:
class F(float):
def __init__(self, spam, eggs):
print "spam=",spam, "eggs=", eggs
>>> f = F(1,2)
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: float() takes at most 1 argument (2 given)
If I modify the constructor to only take a single argument, I get the
following:
class F(float):
def __init__(self, spam):
print "spam=",spam
>>> f = F(3.14)
spam= 3.14
>>> print f
3.14
>>> print f*2
6.28
How is the value "3.14" getting associated with f? Apparently the
base class constructor is called. How come this is happening?