Is passing too many arguments to the constructor considered an anti-pattern?

前端 未结 5 875
独厮守ぢ
独厮守ぢ 2021-01-01 20:31

I am considering using the factory_boy library for API testing. An example from the documentation is:

class UserFactory(factory.Factory):
    class Meta:
            


        
5条回答
  •  萌比男神i
    2021-01-01 20:59

    You could pack the __init__ method's keyword arguments into one dict, and set them dynamically with 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)
    

    However, this has the drawback of disallowing you from supplying arguments without naming them - x = User("Mr", "Kevin") works with your original code, but not with this code.

提交回复
热议问题