简体   繁体   中英

TyperError: object() takes no parameters

Here's my class :

    class Person:

    def __new__(cls, first, last):
        print("Calling __new__() method of class {}".format(cls))
        return object.__new__(cls, first, last)

    def __init__(self, first, last):
        """Constructor of Person working instance
        (attribute initialization)"""
        print("Calling __init__()")
        self.first = first
        self.last = last
        self.age = 23
        self.residency = "Lyon"

    def __repr__(self):
        return "Person : {} {} aged {} years living in {}".format(self.first, self.last, self.age, self.residency)

person = Person("Doe", "John")
print(person)

and I'm getting the following error that I cannot seem to resolve:

Calling __new__() method of class <class '__main__.Person'>
Traceback (most recent call last):
  File "test.py", line 20, in <module>
    person = Person("Doe", "John")
  File "test.py", line 6, in __new__
    return object.__new__(cls, first, last)
TypeError: object() takes no parameters

What am I doing wrong? Thank you and cheers!

The object constructor takes no additional parameters. The right implementation of the __new__ method should not pass the last two parameters:

def __new__(cls, first, last):
    print("Calling __new__() method of class {}".format(cls))
    return object.__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