编程语言
首页 > 编程语言> > python – 是否将过多的参数传递给构造函数被认为是反模式?

python – 是否将过多的参数传递给构造函数被认为是反模式?

作者:互联网

我正在考虑使用factory_boy库进行API测试.文档中的一个例子是:

class UserFactory(factory.Factory):
    class Meta:
        model = base.User

    first_name = "John"
    last_name = "Doe"

为此,我们需要将first_name,last_name等作为参数传递给base.User()类的__init __()方法.但是,如果您有许多参数,则会导致以下情况:

class User(object):

    GENDER_MALE = 'mr'
    GENDER_FEMALE = 'ms'

    def __init__(self, title=None, first_name=None, last_name=None, is_guest=None,
             company_name=None, mobile=None, landline=None, email=None, password=None,
             fax=None, wants_sms_notification=None, wants_email_notification=None,
             wants_newsletter=None, street_address=None):

        self. title = title
        self.first_name = first_name
        self.last_name = last_name
        self.company_name = company_name
        self.mobile = mobile
        self.landline = landline
        self.email = email
        self.password = password
        self.fax = fax
        self.is_guest = is_guest
        self.wants_sms_notification = wants_sms_notification
        self.wants_email_notification = wants_email_notification
        self.wants_newsletter = wants_newsletter
        self.company_name = company_name
        self.street_address = street_address

现在的问题是,这种结构是否被视为反模式,如果是,我有哪些替代方案?

谢谢

解决方法:

您可以将__init__方法的关键字参数打包到一个dict中,并使用setattr动态设置它们:

class User(object):
    GENDER_MALE = 'mr'
    GENDER_FEMALE = 'ms'
    def __init__(self, **kwargs):
        valid_keys = ["title", "first_name", "last_name", "is_guest", "company_name", "mobile", "landline", "email", "password", "fax", "wants_sms_notification", "wants_email_notification", "wants_newsletter","street_address"]
        for key in valid_keys:
            setattr(self, key, kwargs.get(key))

x = User(first_name="Kevin", password="hunter2")
print(x.first_name, x.password, x.mobile)

但是,这有一个缺点,即不提供参数而不提供参数 – x = User(“Mr”,“Kevin”)可以使用原始代码,但不能使用此代码.

标签:python,factory-boy
来源: https://codeday.me/bug/20191008/1870902.html