简体   繁体   中英

Too many constructor arguments

I encounter this problem where I have to pass a lot of arguments to the constructor in order to instantiate the class. I have no clue how to tackle this problem.

user = SpecialStudent(John, Doe, johndoe@example.com, 0612345678, 9988778, hello)

class User(Base):
    def __init__(self, name, surname, email):
        self.name = name
        self.surname = surname
        self.email = email

class Student(User):
    def __init__(self, name, surname, email, phone, student_number):
        super(Student, self).__init__(name, surname, email)
        self.phone = phone
        self.student_number = student_number

class SpecialStudent(Student):
    def __init__(self, name, surname, email, phone, student_number, random_param):
        super(SpecialStudent, self).__init__(name, surname, email, phone, student_number)
        self.random_param = random_param

I have thought about the builder pattern or factory, but I don't know which pattern will tackle this problem or if there is a other way to do this.

after small modifications:

class User(object):
    def __init__(self, name, surname, email):
        self.name = name
        self.surname = surname
        self.email = email

class Student(User):
    def __init__(self, name, surname, email, phone, student_number):
        super(Student, self).__init__(name, surname, email)
        self.phone = phone
        self.student_number = student_number

class SpecialStudent(Student):
    def __init__(self, name, surname, email, phone, student_number, random_param):
        super(SpecialStudent, self).__init__(name, surname, email, phone, student_number)
        self.random_param = random_param

user = SpecialStudent("John", "Doe", "johndoe@example.com", "0612345678", "9988778", "hello")
  1. your Base class is not defined
  2. dont use constructor before class declaration
  3. your inputs are not declared (in my code all inputs are strings)

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