Nereus
Nereus

Reputation: 23

TypeError object takes no parameters

I'm simply trying to make a code how to use super and __new__. Here's the code:

class Person(object):
    def __new__(cls, name, age):
        print('__new__called')
        return super(Person, cls).__new__(cls, name, age)
    def __init__(self, name, age):
        print('__init__called')
        self.name = name
        self.age = age
    def __str__(self):
        return('<Person:%s(%s)>'%(self.name, self.age))
if __name__ == '__main__':  
    piglei = Person("piglei", 24)
    print(piglei)

Python raises a TypeError and says something about line 4, object() takes no parameters.

Upvotes: 2

Views: 153

Answers (1)

Dimitris Fasarakis Hilliard
Dimitris Fasarakis Hilliard

Reputation: 160407

object.__new__ doesn't accept any arguments. Your super call in __new__ will fail:

return super(Person, cls).__new__(cls, name, age)

since you also pass name and age up to object.__new__.

You don't need to pass these up to object; either drop the __new__ definition all together or, don't pass any of the arguments to it:

return super(Person, cls).__new__(cls)

Either way, there's really no reason to use __new__ here but I'm guessing you're experimenting. If you are, take note that you can also drop Person and cls in super and use it's zero argument form, i.e:

return super().__new__(cls)

Upvotes: 1

Related Questions