简体   繁体   English

构造函数参数过多

[英]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) 您的输入未声明(在我的代码中,所有输入均为字符串)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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