简体   繁体   中英

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 .

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, ie:

return super().__new__(cls)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM