[Python-Dev] py3k: TypeError: object.__init__() takes no parameters

Nick Craig-Wood nick at craig-wood.com
Fri Jan 16 13:16:41 CET 2009


I've noticed with latest python 3.1 checkout (68631) if I have this
object hierarchy with a default __init__ in the superclass to be used
by the subclasses which don't necessarily need an __init__ it blows up
with a TypeError.

class Field(object):
    def __init__(self, data):
        """Default init for the subclasses"""
        print("init class=%r, self=%r" % (self.__class__.__name__, self))
        super(Field, self).__init__(data)
        self.data = self.orig = data

class IntegerField(Field):
    def __init__(self, data):
        """Overridden init"""
        super(IntegerField, self).__init__(data)
        self.data = int(data)

class StringField(Field):
    pass

f1 = StringField('abc')
f2 = IntegerField('10')
print("f1=%r" % f1.data)
print("f2=%r" % f2.data)
print(type(f1))
print(type(f2))

It blows up with

init class='StringField', self=<__main__.StringField object at 0xb7d47b4c>
Traceback (most recent call last):
  File "subclass-super-problem-py3k.py", line 17, in <module>
    f1 = StringField('abc')
  File "subclass-super-problem-py3k.py", line 5, in __init__
    super(Field, self).__init__(data)
TypeError: object.__init__() takes no parameters

The exact same code runs under py 2.5 just fine.

I can't think of anything to write in Field.__init__ to tell whether
super is about to run __init__ on object.

The problem can be fixed (inelegantly IMHO) like this

class BaseField(object):
    def __init__(self, data):
        """Default init for the subclasses"""
        self.data = self.orig = data

class Field(BaseField):
    def __init__(self, data):
        """Another Default init for the subclasses"""
        super(Field, self).__init__(data)

class IntegerField(Field):
    def __init__(self, data):
        """Overridden init"""
        super(IntegerField, self).__init__(data)
        self.data = int(data)

class StringField(Field):
    pass

f1 = StringField('abc')
f2 = IntegerField('10')
print("f1=%r" % f1.data)
print("f2=%r" % f2.data)
print(type(f1))
print(type(f2))

Is this a bug or a feature?  Is there a better work-around?

-- 
Nick Craig-Wood <nick at craig-wood.com> -- http://www.craig-wood.com/nick


More information about the Python-Dev mailing list